200

在模块内,控制器可以从外部控制器继承属性:

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

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

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

示例来自:死链接http ://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html

模块内的控制器也可以从兄弟继承吗?

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
});

第二个代码不起作用,因为$injector.invoke需要一个函数作为第一个参数并且没有找到对ParentCtrl.

4

9 回答 9

292

是的,它可以,但您必须使用该$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
});
于 2013-11-27T00:24:04.603 回答
20

如果您使用的是vm控制器语法,这是我的解决方案:

.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}));
})

不幸的是,您不能使用$controller.call(vm, 'BaseGenericCtrl'...), 将当前上下文传递给闭包 (for reload()) 函数,因此只有一种解决方案是使用this内部继承函数来动态更改上下文。

于 2015-12-06T02:05:49.053 回答
8

我认为,您应该使用工厂或服务,为两个控制器提供可访问的功能或数据。

这是类似的问题---> AngularJS 控制器继承

于 2013-08-27T09:13:44.607 回答
8

针对gmontague在这个答案中提出的问题,我找到了一种使用 $controller() 继承控制器的方法,并且仍然使用控制器“as”语法。

首先,在继承调用 $controller() 时使用“as”语法:

    app.controller('ParentCtrl', function(etc...) {
        this.foo = 'bar';
    });
    app.controller('ChildCtrl', function($scope, $controller, etc...) {
        var ctrl = $controller('ParentCtrl as parent', {etc: etc, ...});
        angular.extend(this, ctrl);

    });

然后,在 HTML 模板中,如果属性是由 parent 定义的,则用于parent.检索从 parent 继承的属性;如果由 child 定义,则用于child.检索它。

    <div ng-controller="ChildCtrl as child">{{ parent.foo }}</div>
于 2016-04-11T13:01:40.033 回答
5

For those wondering, you can extend component controllers in the same fashion, using the method in the accepted answer.

Use the following approach:

Parent component (to extend from):

/**
 * Module definition and dependencies
 */
angular.module('App.Parent', [])

/**
 * Component
 */
.component('parent', {
  templateUrl: 'parent.html',
  controller: 'ParentCtrl',
})

/**
 * Controller
 */
.controller('ParentCtrl', function($parentDep) {

  //Get controller
  const $ctrl = this;

  /**
   * On init
   */
  this.$onInit = function() {

    //Do stuff
    this.something = true;
  };
});

Child component (the one extending):

/**
 * Module definition and dependencies
 */
angular.module('App.Child', [])

/**
 * Component
 */
.component('child', {
  templateUrl: 'child.html',
  controller: 'ChildCtrl',
})

/**
 * Controller
 */
.controller('ChildCtrl', function($controller) {

  //Get controllers
  const $ctrl = this;
  const $base = $controller('ParentCtrl', {});
  //NOTE: no need to pass $parentDep in here, it is resolved automatically
  //if it's a global service/dependency

  //Extend
  angular.extend($ctrl, $base);

  /**
   * On init
   */
  this.$onInit = function() {

    //Call parent init
    $base.$onInit.call(this);

    //Do other stuff
    this.somethingElse = true;
  };
});

The trick is to use named controllers, instead of defining them in the component definition.

于 2017-01-14T22:41:51.763 回答
5

好吧,我以另一种方式做到了这一点。就我而言,我想要一个在其他控制器中应用相同功能和属性的功能。我喜欢它,除了参数。这样,你所有的 ChildCtrls 都需要接收 $location。

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

function BaseCtrl ($scope, $location) {
    $scope.myProp = 'Foo';
    $scope.myMethod = function bar(){ /* do magic */ };
}

app.controller('ChildCtrl', function($scope, $location) {
    BaseCtrl.call(this, $scope, $location);

    // it works
    $scope.myMethod();
});
于 2015-09-25T13:22:01.967 回答
2

如已接受的答案中所述,您可以通过调用:$controller('ParentCtrl', {$scope: $scope, etc: etc});在您的子控制器中“继承”父控制器对 $scope 和其他服务的修改。

但是,如果您习惯于使用控制器 'as' 语法,例如在

<div ng-controller="ChildCtrl as child">{{ child.foo }}</div>

如果foo在父控制器中设置(通过this.foo = ...),子控制器将无权访问它。

如评论中所述,您可以将 $controller 的结果直接分配给范围:

var app = angular.module('angularjs-starter', []);
app.controller('ParentCtrl ', function(etc...) {
    this.foo = 'bar';
});
app.controller('ChildCtrl', function($scope, $controller, etc...) {
    var inst = $controller('ParentCtrl', {etc: etc, ...});

    // Perform extensions to inst
    inst.baz = inst.foo + " extended";

    // Attach to the scope
    $scope.child = inst;
});

注意:然后您必须从 中删除 'as' 部分ng-controller=,因为您在代码中指定实例名称,而不是模板。

于 2015-06-19T20:35:07.083 回答
2

我正在使用“Controller as”语法vm = this并想继承一个控制器。如果我的父控制器有一个修改变量的函数,我会遇到问题。

使用IProblemFactorySalman Abbas 的答案,我执行了以下操作来访问父变量:

(function () {
  'use strict';
  angular
      .module('MyApp',[])
      .controller('AbstractController', AbstractController)
      .controller('ChildController', ChildController);

  function AbstractController(child) {
    var vm = child;
    vm.foo = 0;
    
    vm.addToFoo = function() {
      vm.foo+=1;
    }
  };
  
  function ChildController($controller) {
    var vm = this;
    angular.extend(vm, $controller('AbstractController', {child: vm}));
  };
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="ChildController as childCtrl" layout="column" ng-cloak="" ng-app="MyApp">
  <button type="button" ng-click="childCtrl.addToFoo()">
    add
  </button>
  <span>
      -- {{childCtrl.foo}} --
  </span>
</div>

于 2016-08-18T13:15:03.903 回答
0

您可以使用简单的 JavaScript 继承机制。也不要忘记传递一个必要的角度服务来调用 .call 方法。

//simple function (js class)
function baseCtrl($http, $scope, $location, $rootScope, $routeParams, $log, $timeout, $window, modalService) {//any serrvices and your 2

   this.id = $routeParams.id;
   $scope.id = this.id;

   this.someFunc = function(){
      $http.get("url?id="+this.id)
      .then(success function(response){
        ....
       } ) 

   }
...
}

angular
        .module('app')
        .controller('childCtrl', childCtrl);

//angular controller function
function childCtrl($http, $scope, $location, $rootScope, $routeParams, $log, $timeout, $window, modalService) {      
   var ctrl = this;
   baseCtrl.call(this, $http, $scope, $location, $rootScope,  $routeParams, $log, $timeout, $window, modalService);

   var idCopy = ctrl.id;
   if($scope.id == ctrl.id){//just for sample
      ctrl.someFunc();
   }
}

//also you can copy prototype of the base controller
childCtrl.prototype = Object.create(baseCtrl.prototype);
于 2017-04-05T10:08:20.887 回答