可以在AngularJS控制器从同一模块中的另一个控制器继承? [英] Can an AngularJS controller inherit from another controller in the same module?

查看:215
本文介绍了可以在AngularJS控制器从同一模块中的另一个控制器继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个模块,控制器可以继承来自外部控制器属性:

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

例如,通过:<一href=\"http://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html\">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
});

第二code,因为 $ injector.invoke 不起作用,需要一个函数作为第一个参数,未找到引用 ParentCtrl

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

推荐答案

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

Yes, it can but you have to use the $controller service to instantiate the controller instead:-

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

这篇关于可以在AngularJS控制器从同一模块中的另一个控制器继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆