4

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.

4

2 回答 2

3

服务(不是控制器)应该拥有域模型,并为应用程序的其余部分(通常是控制器)提供模型 API以供使用。

我建议至少提供两种服务,一种用于您的新闻提要,一种用于您的个人资料,也许还有一种用于任何共享功能(这些功能可以作为参数传递给集合或单个帖子)。将适当的服务注入每个控制器。

“外观”应该在您使用 ng-view 或 ng-include 拉入的 HTML 模板中。模板的 ng-repeat 将引用作为 $scope 属性的集合,该属性是对存储在您的一项服务中的数据的引用。

有关新闻提要服务的示例,以及控制器如何获取对数据的引用,请参阅服务是否应该公开它们的异步性?

我不必担心重复使用 $http 服务所需的代码并在每个服务中返回一个承诺。有一天,您的个人资料页面可能会开始看起来/行为与您的新闻源页面不同。

于 2013-07-03T16:59:00.367 回答
1

将用于格式化和显示的逻辑拉入实用角度服务 (app.factory)。然后您可以将其注入两个控制器并以这种方式共享逻辑。

于 2013-07-03T16:24:01.873 回答