Can an AngularJS controller inherit from another controller in the same module?

Within a module, a controller can inherit properties from an outside controller:

var app = angular.module('angularjs-starter', []);

var ParentCtrl = function ($scope, $location) {
};

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

Example via: Dead link : http://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html

Can also a controller inside a module inherit from a sibling?

var app = angular.module('angularjs-starter', []);

app.controller('ParentCtrl ', function($scope) {
  //I'm the sibling, but want to act as parent
});

app.controller('ChildCtrl', function($scope, $injector) {
  $injector.invoke(ParentCtrl, this, {$scope: $scope}); //This does not work
});

The second code does not work since $injector.invoke requires a function as first parameter and does not find the reference to ParentCtrl .


是的,它可以,但你必须使用$controller服务实例化控制器: -

var app = angular.module('angularjs-starter', []);

app.controller('ParentCtrl', function($scope) {
  // I'm the sibling, but want to act as parent
});

app.controller('ChildCtrl', function($scope, $controller) {
  $controller('ParentCtrl', {$scope: $scope}); //This works
});

In case you are using vm controller syntax, here is my solution:

.controller("BaseGenericCtrl", function ($scope) {

    var vm = this;
    vm.reload = reload;
    vm.items = [];

    function reload() {
        // this function will come from child controller scope - RESTDataService.getItemsA
        this.getItems();
    }
})

.controller("ChildCtrl", function ($scope, $controller, RESTDataService) {
    var vm = this;
    vm.getItems = RESTDataService.getItemsA;
    angular.extend(vm, $controller('BaseGenericCtrl', {$scope: $scope}));
})

Unfortunately, you can't use $controller.call(vm, 'BaseGenericCtrl'...) , to pass current context into closure (for reload() ) function, hence only one solution is to use this inside inherited function in order to dynamically change context.


I think,you should use factory or service,to give accessible functions or data for both controllers.

here is similar question ---> AngularJS controller inheritance

链接地址: http://www.djcxy.com/p/77854.html

上一篇: AngularJS:将服务注入HTTP拦截器(循环依赖)

下一篇: AngularJS控制器能否继承同一模块中的另一个控制器?