2013-07-31 114 views
1

嗨我有两个弹出式指令在同一页上。问题是当我点击一个他们都弹出。不同范围的多个AngularJS指令

如何隔离每个范围,以便只弹出被点击的弹出窗口?

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

回答

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

+0

是的这个作品了。唯一的是我不喜欢使用ng-init,因为它在我看来是逻辑。 – otissv

+0

好吧,您可以将该初始化逻辑移动到控制器。我只是想演示代码并简化一下。 – zsong

1

为了确保每个指令,因为不同的范围,你可以一个scope : true添加到您的指令函数返回的对象。

你一定要检查出documentation(“写入指令(长版)”),它解释了scope属性,如何范围隔离,绑定参数等方面的力量......

stackoverflow question提供了更好的解释。

+0

范围:因为它从弹出指令隔离$ scope.popup真的不起作用。目前该文档已关闭,因此会读取您的链接。 – otissv

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; 
    } 
    } 
+0

你确定它正在工作吗?这并没有太大的意义,因为第二个'this.popup'处于关闭状态,并且与第一个'this.popup'完全不同。 – zsong

+0

噢我还除去触发'<弹出类=“弹出”> Show Popup 我弹出 otissv

+0

'是第一this.popup可以去除 – otissv