AngularJS $watch newValue is undefined

后端 未结 2 1452
不思量自难忘°
不思量自难忘° 2021-01-07 11:53

I am trying to make a alert service with a directive. It is in the directive part I have some trouble. My have a directive that looks like this:

angular.modu         


        
相关标签:
2条回答
  • 2021-01-07 12:31

    try like this , angular fires your watcher at the first time when your directive initialized

    angular.module('alertModule').directive('ffAlert', function() {
      return {
        templateUrl: 'components/alert/ff-alert-directive.html',
        controller: ['$scope','alertService',function($scope,alertService) {
          $scope.alerts = alertService;
        }],
        link: function (scope, elem, attrs, ctrl) {
          scope.$watch(scope.alerts, function (newValue, oldValue) {
            if(newValue === oldValue) return;
            console.log("alerts is now:",scope.alerts,oldValue, newValue);
            for(var i = oldValue.list.length; i < newValue.list.length; i++) {
              scope.alerts.list[i].isVisible = true;
              if (scope.alerts.list[i].timeout > 0) {
                $timeout(function (){
                  scope.alerts.list[i].isVisible = false;
                }, scope.alerts.list[i].timeout);
              }
            }
          }, true);
        }
      }
    });
    
    0 讨论(0)
  • 2021-01-07 12:33

    if you have jQuery available, try this

    if(jQuery.isEmptyObject(newValue)){
          return;
    }
    

    inside scope.$watch

    0 讨论(0)
提交回复
热议问题