0

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?

1
  • you should be using isolated scopes for this Commented Apr 29, 2013 at 7:00

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.