我有一个指令
angular.module('eventsApp')
.directive('calendar', function(){
return {
restrict: 'E',
template: '<div id="eventCal"></div>',
scope: {
events: '='
},
link: function(scope, elem, attrs){
var eventCal = $('#eventCal');
eventCal.fullCalendar({
handleWindowResize: true,
events: scope.events.list
});
scope.$watch('events', function(newModel, oldModel){
console.log(newModel);
console.log(newModel.list);
eventCal.fullCalendar('removeEvents');
eventCal.fullCalendar('addEventSource', newModel.list);
});
}
}
});
带有标记
<calendar events="events"></calendar>
并带有 Controller
angular.module('eventsApp')
.controller('EventsCtrl', ['$scope', 'calendarService',
function ($scope, calendarService) {
$scope.events = {
list: []
};
$scope.$on('configLoaded', function(event, settings){
calendarService.init(settings);
calendarService.getEvents($scope.view);
});
$scope.$on('eventsLoaded', function(event, events){
angular.forEach(events, function(value, key){
$scope.events.list.push(value);
$scope.$broadcast('eventsReady', $scope.events);
});
});
}]);
scope.$watch
方法似乎不起作用。 console.logs 触发一次,并在触发时将 newModel 显示为空(访问其属性 list
返回 undefined
),但该对象被正确引用,因为 console.log (newModel)
显示填充的模型(即,该对象显然是在 watch 运行后填充的)。如果对象发生变化,为什么 watch 不再被调用?还有其他方法可以检查范围的更改吗?
最佳答案
尝试:
scope.$watch('events', function(newModel, oldModel){
console.log(newModel);
console.log(newModel.list);
eventCal.fullCalendar('removeEvents');
eventCal.fullCalendar('addEventSource', newModel.list);
}, true);
效率有点低,但应该可以。最后需要 true
才能使监视递归。或者,您可以直接观看 events.list
。在这种情况下,就不需要 true
了。
关于javascript - $scope.$watch 没有在指令中被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890215/