모듈 내에서 컨트롤러는 외부 컨트롤러에서 속성을 상속 할 수 있습니다.
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
.
답변
예, 가능하지만 $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
});
답변
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
를 동적으로 변경하기 위해 상속 된 함수 내부 를 사용하는 솔루션은 하나뿐입니다 .
답변
답변
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에 의해 정의 된 경우 child.
이를 사용 하여 검색하십시오.
<div ng-controller="ChildCtrl as child">{{ parent.foo }}</div>
답변
글쎄, 나는 다른 방법으로 이것을했다. 필자의 경우 다른 컨트롤러에서 동일한 기능과 속성을 적용하는 기능을 원했습니다. 매개 변수를 제외하고는 마음에 들었습니다. 이런 식으로, 귀하의 모든 ChildCtrl은 $ 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();
});
답변
궁금한 점이 있으시면 허용되는 답변의 방법을 사용하여 동일한 방식으로 구성 요소 컨트롤러를 확장 할 수 있습니다.
다음 접근법을 사용하십시오.
상위 컴포넌트 (확장) :
/**
* 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;
};
});
하위 구성 요소 (확장 된 구성 요소) :
/**
* 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;
};
});
요령은 컴포넌트 정의에서 컨트롤러를 정의하는 대신 명명 된 컨트롤러를 사용하는 것입니다.
답변
허용 된 답변에 언급 된 $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;
});
참고 : 그런 다음 있어야 에서 ‘로’부분을 제거하지 ng-controller=
더 이상 템플릿을 코드에서 인스턴스 이름을 지정하고 있기 때문에.
