[英]Angular directive, binding click event to outside element not working
我正在嘗試創建一個自定義事件以與Angular進行切換。 該指令稱為可切換。
一開始聽起來很瑣碎,但棘手的一點是,我希望能夠使用頁面上的任何按鈕或鏈接進行切換。
我寫的代碼如下
指示
'use strict';
angular.module('onsComponents')
.directive('togglable', function() {
return {
restrict: 'A',
transclude: true,
scope: {
togglerId: '@',
show: '@'
},
link: function(scope, element, attrs) {
if (!scope.togglerId) {
console.error("Toggler id must be given")
return
}
scope.visible = (scope.show === 'true')
scope.toggle = function() {
alert("Before " + scope.visible)
scope.visible = !scope.visible
alert("After " + scope.visible)
}
//Bind click event to given dom element
angular.element('#' + scope.togglerId).bind("click", function() {
scope.toggle()
})
},
templateUrl: 'app/components/toggler/toggler.html'
}
})
模板
<div ng-transclude ng-show="visible">
</div>
風景
<a href="" id="toggleButton" >Click me to toggle</a>
<div togglable toggler-id="toggleButton">
Hey
</div>
切換鏈接似乎有效。 單擊鏈接后,我可以看到警報。 麻煩的是內容沒有出現。 似乎該鏈接與內容實際上不在同一范圍內,當我這樣做時會創建另一個范圍。
如果我按如下所示在模板內移動單擊鏈接,則它將起作用。 但這不是我真正想要的。
<!-- Move the link inside template -->
<a href="" ng-click="toggle()" >Click me to toggle</a>
<div ng-transclude ng-show="visible">
</div>
那么我該如何實現呢?
為此,創建兩個指令和將它們鏈接在一起的服務更具棱角感 。 粗略概述:
app.service('toggleService', function() {
var toggleables = {};
this.registerToggleable = function(key, f) {
toggleables[key] = f;
}
this.toggle = function(key) {
var f = toggleables[key];
f();
}
});
app.directive('toggler', function(toggleService) {
return {
link: function(scope, elem, attrs) {
elem.bind("click", function() {
toggleService.toggle(attrs.toggler);
// because the event handler operates outside of angular digest cycle
scope.$apply();
});
}
}
})
app.directive('toggleable', function(toggleService) {
return {
link: function(scope, elem, attrs) {
function toggle() {
scope.visible = !scope.visible;
}
toggleService.registerToggleable(attrs.toggleable, toggle);
}
}
});
除了在范圍上設置變量外,上面的代碼需要進行調整以實際執行任何操作,但是您可以像這樣使用兩者:
<a href="" toggler="foo" >Click me to toggle</a>
<div toggleable="foo">
Hey
</div>
這樣,您就可以在元素本身上聲明切換功能,而沒有基於ID的查找魔術。
每次更改Angular 在 Angular 之外監視的內容時,都必須調用scope.$apply()
。 在外面,我是指使用jQuery API綁定的事件-或除Angular的本機ng-click
等以外的任何其他方式。
因此:
scope.toggle = function() {
scope.visible = !scope.visible;
scope.$apply();
}
要么:
scope.toggle = function() {
scope.$apply(function() {
scope.visible = !scope.visible;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.