Łuk*_*ski 4 javascript 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>
Run Code Online (Sandbox Code Playgroud)
指令:
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'));
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
该模型month是在app中声明的模型:
value('month', moment());
Run Code Online (Sandbox Code Playgroud)
这是代码:http://jsfiddle.net/EEVGG/11/
正如您所见,代码的月份和年份部分没有变化,而应该是因为calendar-day属性中的值是正确的.
您希望监视范围属性"月"的更改,而不是您在模块上定义的月份对象.为此,请将watchExpression更改为'month'(String):
scope.$watch('month', function (value) {
var currentDate = moment(attrs.calendarDay, "DD-MM-YYYY");
element.text(currentDate.format('DD-MM-YYYY'));
}, true);
Run Code Online (Sandbox Code Playgroud)
还要设置观察器以根据对象相等性(最后一个参数$watch)比较更改,因为月份对象将相同,只有一些属性会更改.有关此检查$ watch文档的更多信息.
jsfiddle:http://jsfiddle.net/bmleite/EEVGG/12/
| 归档时间: |
|
| 查看次数: |
5976 次 |
| 最近记录: |