AngularJS指令检测在模型属性更改中传递

时间:2014-07-22 09:02:06

标签: angularjs directive

我有一个孤立范围的指令。我想检测作为父作用域变量的属性的更改。

到目前为止,我有以下内容:

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


app.controller("ctrl", function($scope, $timeout) {

  $timeout(function() {
    console.log("called");

    $scope.isReady = true;
    $scope.$apply();
  }, 2000);


});

app.directive("car", function($log) {
  return {
    scope: {
      make: "=carMake"
    },
    restrict: 'E',
    template: "<strong ng-bind='make'></strong>",
    link: function(scope, elem, attrs) {

      scope.$watch(attrs.shouldDo, function(value) {
        var val = value || null;
        if (val) {
          $log.info(scope.$eval(attrs.shouldDo));
        }
      }, true);

    }
  }
});

http://fiddle.jshell.net/8Qhuk/

如果我将范围设置为false它可以正常工作,但是我需要它来处理隔离范围。

1 个答案:

答案 0 :(得分:4)

只需将scope部分写为:

 scope: {
        make : "=carMake",
        shouldDo: '='
    },

修正演示 Fiddle

指令示例:

app.directive("car", function($log) {
    return {
        scope: {
            make: "=carMake",
            shouldDo: '='
        },
        restrict: 'E',
        template: "<strong ng-bind='make'></strong>",
        link: function(scope, elem, attrs) {    

            scope.$watch(function() {
                return scope.shouldDo
            },
            function(newValue, oldValue) {
                var val = newValue || null;
                if (val) {
                    $log.info(scope.shouldDo);
                }
            });    
        }
    }
});

watch我们只听一个变通。您不需要true标志


顺便说一句,你可以使用 bind一次进行只读

 scope: {
        make : "=carMake",
        shouldDo: '@'
    },
HTML时的

<car car-make="make" should-do="{{isReady}}"></car>

演示2 Fiddle