How to split single controller in multiple js files in angularjs [closed]

空扰寡人 提交于 2019-12-17 18:15:22

问题


I am rewriting a large application from silver-light to angularjs, while doing it, I am realizing that each of my controller js file is spanning 2000-3000 lines of code. All of my code is heavily dependent on scope variables. Wondering if there is any opportunity to split single controller js file into multiple js files? Any pointer would be appreciated.


回答1:


Use multiple controller to handle the task in your page. If using a larg controller is unavoidable ,you can split the definition to multiple files by passing the scope to another method and then define the rest of methods there.

In the first file:

app.controller('CtrlA', function($scope){
app.expandControllerA($scope);

});

In the second file

app.expandControllerA = function($scope)
{

}

You can pass any variable or dependencies to expandControllerA function.




回答2:


You can also create a base controller and use $controller service to create derived controllers.

For example:

function BaseCtrl($scope, options) {
    var vm = this;

    // code
    return vm;
}

function ChildCtrl($controller, $scope) {
    var vm = $controller('BaseCtrl', {
        $scope: $scope,
        options: { }
    });

    // extend view model
    vm.name = '';

    return vm
}

There are other ways to split controllers into separate files, check out this ng-conf video.




回答3:


You could use App.factory or app.service in your angular module, They would be more like inhereting the data in your snippet. so that you can assign the part of data outside the main controller and inherite the assigned variable in your controller.

    app.factory('name of the factory',function(){
return (data)
   )
app.controller('$scope','name of the factory', function(scope, name of the factopry

$scope.new = data;
))


来源:https://stackoverflow.com/questions/25819661/how-to-split-single-controller-in-multiple-js-files-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!