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
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);
});
}
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With