【问题标题】:How to acces model from inside directive when model changes in controller $scope?当控制器 $scope 中的模型更改时,如何从内部指令访问模型?
【发布时间】:2013-05-11 09:37:24
【问题描述】:

我正在尝试获取指令内的值何时从外部更改,并且它似乎不适用于 scope.$watch 或 attrs.$observe。

我有一个小提琴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);
         });

      }
    }
  });

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    如果您想查看数组的内容(而不是其引用),您需要通过将 true 作为最后一个参数传递给 $watch 方法来使用 deep-watch:

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

    http://jsfiddle.net/dVzCP/

    在最新的 AngularJS (1.1.4) 中,事情变得更容易了,因为有一种新方法 (scope.$watchCollection) 专门用于观察集合的浅表元素: http://code.angularjs.org/1.1.4/docs/api/ng.$rootScope.Scope#$watchCollection

    【讨论】:

      猜你喜欢
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多