Reputation: 70466
Here is the fiddle: 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();
});
};
});
So clicking on toggle1 or toggle2 will open both container at the same moment. But I want to toggle them independently. How can I achieve this?
Upvotes: 0
Views: 1320
Reputation: 18081
You have to do something to separate the events. You can provide some additional data in the broadcast:
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>
See my fork: http://jsfiddle.net/vBzkV/
Upvotes: 2