Undrium
Undrium

Reputation: 2678

Reach directives scope from another directive

I have two directives, one which takes care of a list and one which creates an item in the list. The problem is that the directive which creates an item can be created anywhere in the dom. When I have created an item, how do I tell the other directive to update the list so I can list the new item?

The create-directive has a function called createItem which should call the other list-directives function "updateList". I have a service which both can use but I'd rather not fiddle with the scope in the service.

Am I thinking wrong here? Both are really needed for reusability but since their scopes are at closest siblings it's hard to reach them from each other.

Upvotes: 0

Views: 132

Answers (1)

Chnoch
Chnoch

Reputation: 772

What you can do is use angular events to trigger the "updateList" function.

Make the list-directive listen to an event like this:

//Whenever the 'update-list' event is broadcasted, the updateList() function will be called
scope.$on('update-list', updateList);

To broadcast the event from the create-directive you need to inject the $rootScope. With that you can now trigger the event:

$rootScope.$broadcast('update-list');

While events work fine in that scenario, please use them cautiously. If you have too many events all across your application it might be difficult to figure out what happens where and why.

The alternative that you would have is completely manage the list in the service that both directives use. In the list-directive you could bind to the list from the service, so that it'll get automatically updated whenever the list in the service changes. With that you don't need to change something in the scope of the directive from the Service, which should be avoided.

Upvotes: 1

Related Questions