How to reuse one controller for 2 different views?

落花浮王杯 提交于 2019-12-03 04:27:51

Under the given conditions I might be doing something like

function MyCommonCtrl(type){
    return function($scope, $http) {
        $scope.x = 5;

        if(type = 't1'){
            $scope.domore = function(){
            }
        }

        ....
        ....
    }
}

angular.module('ng').controller('Type1Ctrl', ['$scope', '$http', MyCommonCtrl('t1')]);
angular.module('ng').controller('Type2Ctrl', ['$scope', '$http', MyCommonCtrl('t2')]);

Then

<div ng-controller="Type1Ctrl"></div>

and

<div ng-controller="Type2Ctrl"></div>

I don't know your specific set-up but your 2 controllers could inherit from a common ancestor.

Type1Ctrl.prototype = new MyCtrl();
Type1Ctrl.prototype.constructor = Type1Ctrl;

function Type1Ctrl() {
  // constructor stuff goes here
}

Type1Ctrl.prototype.setScope = function() {
  // setScope
};

Type2Ctrl.prototype = new MyCtrl();
Type2Ctrl.prototype.constructor = Type2Ctrl;

function Type2Ctrl() {
  // constructor stuff goes here
}

Type2Ctrl.prototype.setScope = function() {
  // setScope
};

I also faced similar problem and scope inheritance solved my problem. I wanted to "reuse" a controller to inherit common state/model ($scope) and functionality (controller functions attached to $scope) As described in the "Scope Inheritance Example" I attach parent controller to an outer DOM element and child controller to the inner. Scope and functions of parent controller "merge" seamlessly into the child one.

Here is another option. Slightly modified from this blog post

app.factory('ParentCtrl',function(){
    $scope.parentVar = 'I am from the parent'
  };
});

app.controller('ChildCtrl', function($scope, $injector, ParentCtrl) {
  $injector.invoke(ParentCtrl, this, {$scope: $scope});
});

here is a plunker

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