Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple directive instances and events

I have a directive that I use multiple times on a page. It fires an event when the state changes, and the controller then handles the event.

The problem is that the event is fired twice. I get why this happens, but I am stuck either trying to find a workaround or better design. Any tips?

Plunker example: http://plnkr.co/edit/xObOvi253qejphU5arFr

like image 829
Jason Capriotti Avatar asked Aug 01 '13 14:08

Jason Capriotti


1 Answers

You need to define isolated scope to make the directive reusable. A simple fix is to just add scope: {} to create an isolated scope so when you click on each button, it only fire once.

app.directive('myDirective', function () {
  return {
    restrict: 'E',
    scope: {},  // Add this line to create an isolated scope
    template: '<div>Foo: {{foo}}</div><button ng-click="incrementFoo()">Increment Foo</button>',
    controller: function ($scope) {
      $scope.foo = 0;
      $scope.incrementFoo = function () {
        $scope.foo += 1;
      };

      $scope.$watch('foo', function () {
        $scope.$emit('fooChanged', {foo: $scope.foo});
        console.log($scope);
      });
    }
  };
});
like image 142
zs2020 Avatar answered Nov 15 '22 16:11

zs2020