Angular.js最佳实践 - 扩展的控制器,覆盖控制器默认 [英] Angular.js best practice - extending controllers, overriding controller defaults

查看:204
本文介绍了Angular.js最佳实践 - 扩展的控制器,覆盖控制器默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个真实的角度的问题,我不能绕到我的头。
我喜欢棱角分明,但现在这个问题是窃听了我很多。

Here is a real-life Angular problem I can't wrap my head around. I love Angular, but this issue is bugging me a lot right now.

什么是扩展现有的控制器的功能,并使用扩展的控制器我的应用程序的其他页面上的最佳做法?
换句话说:如何做控制器基业角

What is the best practice to extend an existing controllers's functions, and use the extended controller on an other page of my application? In other words: How to do controller inheritance in Angular?

编辑退出 - 23/09/2014,不认为我原来用例的描述可以帮助游客更好地我这里经过很明白。我认为这disctracts人们从真正的问题。

Edited out - 23/09/2014, dont think the description of my original usecase helps the visitors to understand it better what I'm after here. I think it disctracts people from the real issue.

推荐答案

半年,我认为我完全理解这是怎么回事了。
由于它是在这条信息的评论中指出,最简单的答案是服务。

After half a year I think I understand completely what's going on. As it is pointed out in a comment to this post, the simplest answer is services.

在最理想的情况下,你的所有范围变量都是从工厂/服务聚集值。不过,你可能想用一个额外的功能,使用相同的控制器:$ scope.someFunction(){},并保持休息。在这种情况下,你有一个薄控制器逻辑,这是理想的控制器的设计 - 但仍可能落得个百人以上线code的。你不想在一个其他的控制器被复制,只是因为你需要一些额外的控制器逻辑(如$ scope.someFunction())

In the most optimal case, all your scope variables are values gathered from a factory/service. Still, you might want to use the exact same controller with one extra function: $scope.someFunction(){}, and keep the rest. In this case, you do have a 'thin' controller logic, which is the desirable controller design - but may still end up a hundred or more lines of code. You don't want that being duplicated in an other controller, just because you need some extra controller logic (like $scope.someFunction() )

那你怎么办呢?

答案是这样的:


  1. 确保你做的一切都是为了解决工厂的情况

  2. 如果你是abolutely一定你做了,去的控制器注入:

  1. Make sure that you did everything in order to solve the situation with factories
  2. if you are abolutely certain you did, go for the controller injection:

.controller('childController',函数($范围,$控制器){
  使用严格的;
  $控制器('parentController',{$范围:$范围});
  $ scope.someFunction =功能(){}
})

就这么简单。 - 再次,通常情况下,事情可以与工厂解决。

It's that simple. -- again, usually, things can be solved with factories..

希望对您有所助益;)

这篇关于Angular.js最佳实践 - 扩展的控制器,覆盖控制器默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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