javascript - $scope.$watch 没有在指令中被触发

标签 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){
        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/

相关文章:

javascript - 在循环中使用 $.getJSON 附加到全局变量

javascript - React 大日历没有默认导出

javascript - 单击绘图显示时使标志可见

javascript - 在 Angular JS 中使用 $timeout 进行重复的休息调用

javascript - Angularjs 默认表单错误消息样式/css

javascript - Angular 要求指令打破了我自己的指令

javascript - yii2 中的 Yii2 Ajax 请求

jquery-plugins - Angular 模型更改后刷新 Bootstrap ScrollSpy

javascript - 使用 $http.get 在 Angular 中选择的下拉选项填充表数据

angularjs - 我可以将匿名函数或代码作为指令中的属性吗?