AngularJS在控制器之间共享方法 [英] Angularjs share methods between controller

查看:104
本文介绍了AngularJS在控制器之间共享方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它在一个页面(主页)上显示新闻提要,而在另一页面上,它只为用户(用户个人资料页面)显示提要.

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).

两个页面的外观和行为均相同.内容的变化是由于调用了不同的URL.

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

如何在angularjs中解决此问题?

How to solve this in angularjs?

我有一个主页控制器,该控制器具有用于显示主页的所有方法/逻辑.

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

现在,我需要再有一个控制器来调用另一个URL,并执行与家庭控制器相同的操作.

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

我正在考虑类似父控制器和两个控制器的事情.但看起来在angularjs控制器中,继承是由dom结构决定的.就我而言,它们是两个不同的页面.所以我无法创建dom样式继承.

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.

如果需要,我很乐意为该问题添加更多详细信息.我经历了许多Google搜索结果,但我不知道该怎么做.

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.

推荐答案

服务(而非控制器)应拥有域模型,并提供

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.

外观"应位于使用ng-view或ng-include插入的HTML模板中.模板的ng-repeat将引用一个集合,该集合是一个$ scope属性,它是对存储在您的一项服务中的数据的引用.

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?

我不必担心重复使用$ http服务所需的代码并在每个服务中返回一个promise.有一天,您的个人资料页面的外观/行为可能会与新闻源页面的外观/行为有所不同.

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.

这篇关于AngularJS在控制器之间共享方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆