0

这是小提琴:http: //jsfiddle.net/yFyxL/2/

angular.module("myApp", []) //
.controller('MainController', function($scope) {
    $scope.toggle1 = function() {
        $scope.$broadcast('event:toggle');
    }
    $scope.toggle2 = function() {
        $scope.$broadcast('event:toggle');
    }
}) //
.directive('toggle', function() {
    return function(scope, elem, attrs) {
        scope.$on('event:toggle', function() {
            elem.slideToggle();
        });
    };
});

因此,单击 toggle1 或 toggle2 将同时打开两个容器。但我想独立切换它们。我怎样才能做到这一点?

4

1 回答 1

2

你必须做一些事情来分离事件。您可以在广播中提供一些额外的数据:

angular.module("myApp", []) //
.controller('MainController', function($scope) {
    $scope.toggle1 = function() {
        $scope.$broadcast('event:toggle','1');
    }
    $scope.toggle2 = function() {
        $scope.$broadcast('event:toggle','2');
    }
}) //
.directive('toggle', function() {
    return function(scope, elem, attrs) {
        scope.$on('event:toggle', function(ev,id) {
            if(attrs.toggle === id){ elem.slideToggle(); }
        });
    };
});
<div class="div1" toggle="1">
  <p>This is section #1</p>
</div>
<div class="div2" toggle="2">
  <p>This is section #2</p>
</div>

见我的叉子:http: //jsfiddle.net/vBzkV/

于 2013-04-29T07:13:27.183 回答