这是小提琴: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将同时打开两个容器。但我想独立切换它们。我怎样才能做到这一点?
答案 0 :(得分: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>