2014-07-22 35 views
2

我有一個隔離範圍的指令。我想檢測作爲父範圍變量的屬性的更改。在模型屬性更改中傳遞的角度指令檢測

我見到目前爲止以下內容:

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它的作品,但我需要它有一個孤立的範圍內工作。

回答

2

只要寫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我們只監聽一個varaible。你不需要true標誌


順便說一句,你可以使用綁定一次只讀

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

當HTML:

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

演示2 Fiddle

Yup!
+0

是!這就是訣竅!太好了,謝謝! :) – Mantisimo