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

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

问题描述

这是一个我无法理解的真实 Angular 问题.我喜欢 Angular,但这个问题现在困扰着我很多.

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.

扩展现有控制器的功能并在应用程序的其他页面上使用扩展控制器的最佳实践是什么?换句话说:如何在 Angular 中进行控制器继承?

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,不要认为我的原始用例的描述有助于访问者更好地理解我在这里追求的内容.我认为它分散了人们对真正问题的注意力.

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(){},并保留其余部分.在这种情况下,您确实有一个瘦"控制器逻辑,这是理想的控制器设计 - 但最终可能仍然有一百行或更多行代码.您不希望在其他控制器中复制它,只是因为您需要一些额外的控制器逻辑(例如 $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. 如果你绝对确定你做到了,就去注入控制器:

  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', function ($scope, $controller) {
  'use strict';
  $controller('parentController', {$scope: $scope});
  $scope.someFunction=function(){}
})

就是这么简单.-- 再说一遍,通常情况下,工厂可以解决问题..

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

希望你觉得这有用 ;)

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

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