Directive listens for controller variable change

Just get started with AngularJS and try to find the best practice for listening to events when the variable inside the controller changes. The only way I worked with is to emit, as shown below.

For example:

var app = angular.module("sampleApp", [])

app.controller("AppCtrl", function($scope){
  $scope.elements = [
    {
        name: "test"
    }
  ]

  $scope.addElement = function() {
      $scope.elements.push({
          name: "test" + $scope.elements.length
      })
      $scope.$emit('elementsChanged', $scope.elements);
  }
})

app.directive('render', function() {
  var renderFunc = function() {
      console.log("model updated");
  }
  return {
      restrict: 'E',
      link: function(scope, element, attrs, ngModel) {
         scope.$on('elementsChanged', function(event, args) {
              renderFunc();
         })
      }
  }
})

This seems a bit uncomfortable, and I feel like I'm working against an angular point. I tried to have $ watch on the model, but this does not seem to work. Any help on this would be greatly appreciated, thanks!

+4
source share
1 answer

I assume you are using unstable Angular because $ watchCollection is only in an unstable branch.

$watchCollection(obj, listener)

Shallow , - ( , - ). , .

"Angular" - .

<render collection='elements'></render>

app.directive('render', function() {
  var renderFunc = function() {
      console.log("model updated");
  }
  return {
      restrict: 'E',
      link: function(scope, element, attrs) {
         scope.$watchCollection(attrs.collection, function(val) {
           renderFunc();
         });
      }
  }
})

Angular, true . $watch, , .

$watch(watchExpression, listener, objectEquality)

objectEquality () boolean , .

, , DOM, , . $watchCollection , , renderFunc().

Angular . , , . , .

+3

All Articles