[英]Isolating scope in AngularJS directive
我對Angular很新,我正在嘗試編寫自己的指令來了解這些對象是如何工作的。 我的問題是關於如何隔離我的指令的范圍,所以我可以在同一個控制器中多次使用它。
我在這里創建了一個plunker來更好地解釋這種情況: http ://plnkr.co/edit/NsISESR9sIs5Nf577DX4?p = preview
HTML:
<body ng-controller="MainCtrl">
<button id="button1" ng-click="dummyClickFoo()" wait-button>Foo</button>
<button id="button2" ng-click="dummyClickBar()" wait-button>Bar</button>
</body>
JS:
app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.dummyClickFoo = function() {
$scope.startSpinner();
setTimeout(function() {
$scope.stopSpinner();
}, 3000);
};
$scope.dummyClickBar = function() {
$scope.startSpinner();
setTimeout(function() {
$scope.stopSpinner();
}, 3000);
};
});
app.directive('waitButton', function() {
return {
restrict: 'A',
controller: ['$scope', '$element', function($scope, $element) {
$scope.startSpinner = function() {
alert($element.attr('id'));
};
$scope.stopSpinner = function() {
alert($element.attr('id'));
};
}]
};
});
基本上它可以使用一個按鈕,但它不適用於兩個按鈕,我知道我應該隔離它們的范圍,但我不知道如何...我已經看過周圍的例子,但他們使用額外的屬性來傳遞變量我需要調用我的內部方法。
有人可以幫我弄清楚怎么做嗎? 謝謝!
您可以通過在指令定義中設置scope: {}
來創建隔離范圍。
然后你將無法從你的控制器調用startSpinner
和stopSpinner
,你不應該! 在指令中使用ng-click或綁定指令中的單擊處理程序而不是控制器中的單擊處理程序。 由於你的指令沒有標記,我建議你做后者:
// added after the directive controller definition
link: function(scope, element) {
element.on("click", function() { scope.startSpinner() });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.