Anirudhan J
Anirudhan J

Reputation: 2072

Angularjs share methods between controller

I have an application that displays a news feed on one page (home page) and in another, it displays the feed for the user alone (user profile page).

Both pages look and behave in the same way. The change in content is due to different URLs called.

How to solve this in angularjs?

I have a home controller that has all the methods/logic used to display the home page.

Now I need to have one more controller that calls the other URL and does the same thing as a home controller.

I was thinking of something like the parent controller and two controllers. But it looks like in angularjs controller inheritance is determined by the dom structure. In my case, they are two different pages. So I cant create a dom style inheritance.

I am confused on how to solve this without duplicating the code in both controllers.

I will be happy to add more details to this question if needed. I went through a number of google results but I couldn't figure out how to do this.

Upvotes: 4

Views: 2944

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364697

A service (not a controller) should own the domain model, and provide a model API to the rest of the application (usually controllers) to use.

I suggest at least two services, one for your newsfeed, and one for your profile, and maybe one more for any shared functions (these functions can be passed a collection, or an individual post, as an argument). Inject the appropriate service(s) into each controller.

The "look" should be in an HTML template that you pull in using ng-view or ng-include. The template's ng-repeat will refer to a collection that is a $scope property that is a reference to the data stored in one of your services.

For an example of a newsfeed service, and how a controller can get a reference to the data, see Should services expose their asynchronicity?

I wouldn't worry about repeating the code needed to use the $http service and return a promise in each service. Someday your profile page may start to look/behave differently than your newsfeed page.

Upvotes: 3

frosty
frosty

Reputation: 21762

Pull your logic used to format and display into a utility angular service (app.factory). Then you can inject that into both controllers and share the logic that way.

Upvotes: 1

Related Questions