我有兩個實現獨立功能的指令。我試圖在元素指令中使用attribute指令,但watch不在屬性指令中工作。這裏是jsfiddle鏈接:http://jsfiddle.net/hsyR5/8/監視不在另一個自定義元素指令內使用的自定義屬性指令內工作
我希望isLoaded指令監視被觸發,只要is-loaded屬性值被改變。
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;
}
})
[0] .attributes [ '被加載']的nodeValue whydont只是你直接使用http:/ /jsfiddle.net/hsyR5/9/ –
是的,謝謝你的建議。請解釋爲什麼包裝attrs.isLoaded在函數內工作?感謝您的幫助:) –