[英]Watch is not working inside a custom attribute directive used inside another custom element directive
我有兩個實現獨立功能的指令。 我正在嘗試在元素指令中使用屬性指令,但是監視無法在屬性指令上使用。 這是jsfiddle鏈接: http : //jsfiddle.net/hsyR5/8/
我希望每當更改is-loaded屬性值時都將觸發isLoaded指令手表。
HTML:
<div ng-app="myapp">
<div ng-controller="ReportCtrl">
<mydir is-loaded="false" id="change" expand-me="isExpanded" ng-transclude>
<button ng-click="expandIt()"> Expand</button>
</mydir>
</div>
JavaScript代碼:
var myApp = angular.module('myapp', [])
myApp.directive('mydir', function () {
return {
restrict: 'E',
scope : {
expandMe:'='
},
replace: true,
transclude: true,
template : "<div></div>",
link: function (scope, element, attrs) {
scope.$watch('expandMe', function (){
//load the data
console.log('inside mydir directive');
element[0].attributes['is-loaded'].nodeValue = ''+scope.expandMe;
});
}
};
});
myApp.directive('isLoaded', function () {
return {
restrict : 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.isLoaded, function (){
console.log('isLoaded Changed');
});
}
};
});
myApp.controller('ReportCtrl', function($scope){
$scope.isExpanded = false;
$scope.expandIt = function(){
$scope.isExpanded = !$scope.isExpanded;
}
})
如果將字符串作為第一個參數傳遞,則使用scope.$watch
,它需要匹配一個scope屬性。
您的嘗試將類似於編寫:
scope.$watch("false", function (){
....
});
但是scope.false
是未定義的。
由於您不關注范圍屬性,因此可以使用返回變量的函數作為第一個參數進行觀察
scope.$watch(function (){
return attrs.isLoaded;/* define what to watch*/
}, function(newVal,oldVal
if(newVal !=oldVal){
console.log('isLoaded Changed');
}
});
您還可以使用attrs.$observe
類似於在范圍上使用$watch
在第一個指令中, element[0].attributes
是不必要的,因為屬性已經可以用作link
參數。 您可以使用以下方法更改屬性:
attrs.isLoaded = '' + scope.expandMe;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.