具有不同范围的多个 AngularJS 指令

2024-04-17

您好,我在同一页面上有两个弹出指令。问题是当我点击其中一个时,它们都会弹出。

如何将每个范围相互隔离,以便仅弹出单击的弹出窗口?

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;
            }
        }
    }
})

Demo on jsFiddle http://jsfiddle.net/SEtZu/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有不同范围的多个 AngularJS 指令 的相关文章

随机推荐