2

嗨,我在同一页面上有两个弹出指令。问题是当我单击一个时,它们都会弹出。

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

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

3 回答 3

1

为了确保您的每个指令都作为不同的范围,您可以将 a 添加scope : true到指令函数返回的对象中。

您绝对应该查看文档(“Writing directives (long version)”),它解释了范围属性的功能、如何隔离范围、绑定参数等...

这个stackoverflow 问题提供了更好的解释。

于 2013-07-31T14:28:44.707 回答
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

于 2013-07-31T17:47:26.033 回答
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;
    }
  }
于 2013-07-31T17:40:33.357 回答