Programing

AngularJS 컨트롤러가 동일한 모듈의 다른 컨트롤러에서 상속 할 수 있습니까?

lottogame 2020. 5. 10. 10:14
반응형

AngularJS 컨트롤러가 동일한 모듈의 다른 컨트롤러에서 상속 할 수 있습니까?


모듈 내에서 컨트롤러는 외부 컨트롤러에서 속성을 상속 할 수 있습니다.

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를 동적으로 변경하기 위해 상속 된 함수 내부 를 사용하는 솔루션은 하나뿐입니다 .


두 컨트롤러 모두에 액세스 할 수있는 기능이나 데이터를 제공하려면 공장이나 서비스를 사용해야한다고 생각합니다.

다음은 비슷한 질문입니다 ---> AngularJS 컨트롤러 상속


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

트릭은 컴포넌트 정의에서 정의하는 대신 명명 된 컨트롤러를 사용하는 것입니다.


As mentioned in the accepted answer, you can "inherit" a parent controller's modifications to $scope and other services by calling: $controller('ParentCtrl', {$scope: $scope, etc: etc}); in your child controller.

However, this fails if you are accustomed to using the controller 'as' syntax, for example in

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

If foo was set in the parent controller (via this.foo = ...), the child controller will not have access to it.

As mentioned in comments you can assign the result of $controller directly to the scope:

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

Note: You then must remove the 'as' part from ng-controller=, because you are specifying the instance name in the code, and no longer the template.


I was using the "Controller as" syntax with vm = this and wanted to inherit a controller. I had issues if my parent controller had a function that modified a variable.

Using IProblemFactory's and Salman Abbas's answers, I did the following to have access to parent variables:

(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>


You can use a simple JavaScript inheritence mechanism. Also don't forget pass a needly angular services to invoke of .call method.

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

Refer below mentioned link for AngularJs inheritences feartue.

Controller-Inheritance-in-angularjs

참고URL : https://stackoverflow.com/questions/18461263/can-an-angularjs-controller-inherit-from-another-controller-in-the-same-module

반응형