hh54188
hh54188

Reputation: 15646

Decouple Angular modules

I have a search web app made with AngularJS, which includes two angular modules: the search-keyword-input module and the search-action module.

The first search-keyword-input module has suggest functionality, form validation functionality, and so on. The search-action module's functionality is requesting data and showing sortable results in a table. So each module has its own controller and directive.

Here's the problem: the reason I modularize is, I want modules that could be reused and decoupled. But in this app, the keyword model value in the search-keyword-input module has to be passed into the search action module (the search-action module has to know what keyword to use to perform the search). So how can I pass the value between modules? How can they communicate without being coupled?

I have figured out a way like adding a parent controller and global $scope value:

<div ng-controller="globalController">
    <div ng-controller="keywordController"></div>
    <div ng-controller="searchController"></div>
</div>

So the search-keyword module could set the keyword value on the globalController's $scope and the search-action controller could also obtain that keyword value from the globalController. But I think this makes the modularization meaningless because they are coupled together. What else can I do?

Upvotes: 0

Views: 1384

Answers (1)

ricick
ricick

Reputation: 5786

Your best bet is to create a custom service that can be shared by both controllers, and also used individually, rather than polluting the parent scope.

Upvotes: 1

Related Questions