简体   繁体   English

angular js:将大型控制器拆分为多个文件

[英]angular js: splitting up a large controller into multiple files

I have a controller that is getting rather large.. mostly due to all the input validation I need to do. 我有一个越来越大的控制器..主要是由于我需要做的所有输入验证。 What I'd like to do is split out all the validation functions into a separate "partial controller". 我想做的是将所有验证功能分成一个单独的“部分控制器”。

Normally, I would just create a service and move all the functions in there (which I may still do). 通常,我只是创建一个服务并将所有功能移到其中(我可能仍会这样做)。 The only problem I have with that is: the validation functions, occasionally, need to be aware of the scope. 我唯一的问题是:验证功能有时需要了解范围。 For example, when I'm doing cross validations. 例如,当我进行交叉验证时。 I'm not sure I want to pass the scope to the service. 我不确定是否要将范围传递给服务。

What would be the best approach to this problem? 解决此问题的最佳方法是什么? Use a service..? 使用服务..?

.service("validation-service", function() {
    return {
        populate: function($scope) { //return validator functions }
    };
}); 

Or, is there a way to separate the controller into two files? 或者,是否可以将控制器分为两个文件? Something like this.. 像这样

File 1 文件1

.partialController("myController", function($scope) { /*do normal stuff here*/ });


File 2 文件2

.partialController("myController", function($scope) { /*do validations here*/ });

I would have to agree with Jeff directives will be a lot more useful and possibly reusable if you break it down to its basic function. 我必须同意Jeff指令,如果将其分解为基本功能,它将变得更加有用,并且可能会重用。

For example you could build a password confirm directive or a semantically different directive that checks for equality. 例如,您可以构建密码确认指令或语义上不同的指令来检查是否相等。

Check out this equality directive, it should help: http://plnkr.co/edit/bTFMzV70vjOzwhimVtQL?p=info 看看这个平等指令,它应该会有所帮助: http : //plnkr.co/edit/bTFMzV70vjOzwhimVtQL?p=info


For the example in your Fiddle you could do this instead: (though I am sure you fiddle was a simplified example) 对于您的小提琴中的示例,您可以改为:(尽管我确信您的小提琴是一个简化的示例)

<input name='start' type="number" ng-model="model.start" max="{{model.end}}"/>
<input name='end' type="number" ng-model="model.end" min="{{model.start}}"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM