AngularJS - 指令在模型更新后不会触发
问题描述:
我有日历应用程序。初始化后,所有工作都正常。问题是我改变了我的模型(月)后,指令没有更新新创建的元素。AngularJS - 指令在模型更新后不会触发
视图部分:
<li class="day" ng-repeat="n in [] | range:month.daysInMonth()">
<span class="day-number" calendar-day="{{ n }}-{{ month.format('MM-YYYY') }}">{{ n }}</span>
</li>
的指令:
directive('calendarDay', ['month', function (month) {
return function (scope, element, attrs) {
scope.$watch(month, function (value) {
var currentDate = moment(attrs.calendarDay, "DD-MM-YYYY");
element.text(currentDate.format('DD-MM-YYYY'));
});
};
}]);
模型month
是在应用程序声明的模型为:
value('month', moment());
下面是代码:http://jsfiddle.net/EEVGG/11/
如您所见,代码的月份和年份部分不会更改,但应该是因为calendar-day
属性中的值是正确的。
答
您想要查看在模块上定义的范围属性“month”而非月对象的更改。要做到这一点,改变watchExpression到'month'
(字符串):
scope.$watch('month', function (value) {
var currentDate = moment(attrs.calendarDay, "DD-MM-YYYY");
element.text(currentDate.format('DD-MM-YYYY'));
}, true);
还设置监视器来比较基于对象的平等(的$watch
最后一个参数)的变化,因为这一个月的对象将是相同的,只有一些属性会改变。有关此检查的更多信息$watch documentation。
的jsfiddle:http://jsfiddle.net/bmleite/EEVGG/12/