简体   繁体   English

AngularJS中的控制器中的重构功能

[英]Refactoring functions in controllers in AngularJS

I think I should move some functions from controller in AngularJs to external "container", but where? 我认为我应该将某些功能从AngularJs的控制器移动到外部“容器”,但是在哪里? To service? 要服务吗?

For example: 例如:

.controller('ctrl1', function() {
    $scope.submit = function () {
        ... some code here ...
    });
});

.controller('ctrl2', function() {
    $scope.submit = function () {
        ... the same code here as a function submit of ctrl1 ...
    });
});

Thanks for your time. 谢谢你的时间。

You can use factory for that: 您可以使用工厂:

.factory('someService', function(){
       return {
        submit: function(){
           var some_data='Text';
           return some_data;
        }  

    }
    });

    .controller('ctrl1', function(someService){
       var text=someService.submit();
    });

    .controller('ctrl2', function(someService){
       var text = someService.submit();
    });

Here is the working Plunker 这是工作中的柱塞

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

相关问题 angularJS控制器函数回调 - angularJS controllers functions callback 在控制器AngularJS之间共享功能 - Share functions between controllers AngularJS 在对等angularjs控制器中重构一些重复代码以管理$ intervals的想法 - Ideas for refactoring some duplicated code in peer angularjs controllers for managing $intervals 为AngularJs中的所有控制器共享通用功能 - share common functions for all controllers in AngularJs 在两个不同的控制器AngularJS中使用相同的功能 - Using same functions in 2 different controllers AngularJS 指令与服务重构AngularJS中多个控制器使用的通用方法 - Directive vs. service for refactoring common methods used by multiple controllers in AngularJS 在AngularJS控制器中创建包含功能或具有松散功能的对象会更好吗? - Is it better to create objects containing functionality or have loose functions in AngularJS controllers? AngularJS:在不同的控制器中重复使用控制器功能和模板 - AngularJS : Re-use controller functions and templates in different controllers 定义AngularJS工厂和控制器可访问的全局功能和属性 - Defining global functions and properties accessible by AngularJS factory and controllers AngularJS:如何与其他控制器共享范围函数和变量 - AngularJS: How to share scope functions and variables with other controllers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM