Alexandru R
Alexandru R

Reputation: 8833

How to acces model from inside directive when model changes in controller $scope?

I'm trying to get when the value inside the directive changes from outside and it seems it does not work with either scope.$watch or attrs.$observe.

I have a fiddle here.

angular.module('zippyModule', [])
  .directive('elem', function(){
    return {
      restrict: 'E',
        transclude:true,
        template:"Directive: <span ng-repeat='i in values'>{{i}} </span>",
      scope: { values:'=zippyTitle' },
      link: function(scope, element, attrs) {
         attrs.$observe ('zippyTitle',function(newValue){
             console.log (scope.values);
         });
          scope.$watch ('values',function(newValue){
             console.log (scope.values);
         });

      }
    }
  });

Upvotes: 1

Views: 108

Answers (1)

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

If you want to watch content of an array (and not its reference) you need to use deep-watch by passing true as the last argument to the $watch method:

scope.$watch ('values',function(newValue){
             console.log (scope.values);
}, true);

http://jsfiddle.net/dVzCP/

With the latest AngularJS (1.1.4) things are becoming a bit easier as there is a new method (scope.$watchCollection) specifically created to shallow-watch elements of a collection: http://code.angularjs.org/1.1.4/docs/api/ng.$rootScope.Scope#$watchCollection

Upvotes: 2

Related Questions