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

2 番目のコードは$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

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.から継承されたプロパティを取得するために使用します。子によって定義されている場合は、それchild.を取得するために使用します。

    <div ng-controller="ChildCtrl as child">{{ parent.foo }}</div>
于 2016-04-11T13:01:40.033 に答える
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 に答える