嗨,我在同一页面上有两个弹出指令。问题是当我点击其中一个时,它们都会弹出。
如何将每个范围相互隔离,以便仅弹出单击的弹出窗口?
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>'
}
});
最佳答案
简化指令可能是一个更好的主意,这样作用域就很容易处理。
<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;
}
}
}
})
关于angularjs - 具有不同范围的多个 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971799/