Javascript $scope.$watch未在指令中激发
我有指示Javascript $scope.$watch未在指令中激发,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有指示 angular.module('eventsApp') .directive('calendar', function(){ return { restrict: 'E', template: '<div id="eventCal"></div>', scope: { events: '=' }, link: function(scope, elem, attrs){
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);
});
}
}
});
scope.$watch方法似乎不起作用。console.logs触发一次,并在触发时将newModel显示为空。访问其属性列表时返回未定义,但对象被正确引用,因为console.lognewModel显示已填充的模型,即,对象显然是在运行监视后填充的。如果对象正在更改,为什么不再次调用手表?是否有其他方法检查作用域的更改?尝试:
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。谢谢@bebraw,但这不起作用。console.log仍然为newModel.list显示[],同时为newModel中的list显示填充的数组。我试着直接听事件。还有列表。好的,很难说。确保您使用的是Angular的最新版本。我在1.2 RC中看到了一些类似的小故障。还有,如果你有时间的话,可以建立一个在线演示plunkr。是的,我用的是1.3。我想我只需要在指令中添加一个侦听器$scope.$on,用于加载事件时。感觉有点不舒服,但很管用。这是一个糟糕的想法吗?鉴于您使用的是1.3,您可以尝试scope.$watchCollection'events.list'。。。。有关更好的示例,请参见。如果这不起作用,我想$on是最好的选择。我会调查$watchCollection。还有一件事,我只是使用$timeout来检查以确保对象实际上正在正确更新,这导致事件侦听器正确启动。我知道$timeout调用摘要循环,但我不明白为什么这会影响观察家。有什么想法吗?谢谢你的帮助!
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('events', function(newModel, oldModel){
console.log(newModel);
console.log(newModel.list);
eventCal.fullCalendar('removeEvents');
eventCal.fullCalendar('addEventSource', newModel.list);
}, true);