嗨我在同一页面上有两个弹出指令。问题是,当我点击它们时,它们都会弹出。
如何将每个范围彼此隔离,以便只弹出点击的弹出窗口?
HTML
<popup class="popup">
<trigger>
<a href="#" data-ng-click="showPopup()">Show Popup</a>
</trigger>
<pop>
I popped up
</pop>
</popup>
<popup class="popup">
<trigger>
<a href="#" data-ng-click="showPopup()">Show Popup</a>
</trigger>
<pop>
I popped up too
</pop>
</popup>
popup.js
angular.module('sembaApp')
.directive('popup', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div data-ng-transclude></div>',
controller: function postLink($scope, $element, $attrs) {
$scope.popup = false;
$scope.showPopup = function() {
$scope.popup = !$scope.popup;
}
}
}
})
.directive('trigger', function () {
return {
require: '^popup',
restrict: 'E',
replace: true,
transclude: true,
template: '<div data-ng-transclude></div>',
}
})
.directive('pop', function () {
return {
require: '^popup',
restrict: 'E',
replace: true,
transclude: true,
template: '<aside data-ng-transclude data-ng-show="popup"> yay</aside>'
}
});
答案 0 :(得分:1)
为了确保您的每个指令作为不同的范围,您可以向指令函数返回的对象添加scope : true
。
你一定要查看documentation(“写指令(长版本)”),它解释了scope属性的强大功能,如何隔离作用域,绑定参数等等......
这stackoverflow question提供了更好的解释。
答案 1 :(得分:1)
简化指令可能是一个更好的主意,因此范围很容易处理。
<div ng-app="sembaApp" ng-init="popup1=false;popup2=false;">
<popup class="popup" ng-model="popup1">
<pop data-ng-show="popup1">I popped up</pop>
</popup>
<popup class="popup" ng-model="popup2">
<pop data-ng-show="popup2">I popped up too</pop>
</popup>
</div>
angular.module('sembaApp', [])
.directive('popup', function () {
return {
scope:{
ngModel: '='
},
restrict: 'E',
replace: true,
transclude: true,
template: '<div data-ng-transclude><a href="#" data-ng-click="showPopup()">Show Popup</a></div>',
link: function postLink($scope, $element, $attrs) {
$scope.showPopup = function () {
console.log($scope.ngModel);
$scope.ngModel = !$scope.ngModel;
}
}
}
})
的 Demo on jsFiddle 强>
答案 2 :(得分:0)
通过将$ scope.popup更改为this.popup
来实现它 <popup class="popup">
<a href="#" data-ng-click="showPopup()">Show Popup</a>
<pop>
I popped up
</pop>
</popup>
controller: function postLink($scope, $element, $attrs) {
this.popup = false;
$scope.showPopup = function() {
this.popup = !this.popup;
}
}