2016-06-28 2 views
1

.component()을 사용하여 응용 프로그램을 개발하려면 각도 1.5를 사용하고, 구성 요소와 그의 컨트롤러는 매우 유사합니다. 컨트롤러를 comp1에서 확장하여 comp2와 함께 사용하려면 어떻게해야합니까?컨트롤러 구성 요소를 확장하십시오 - angularjs

각 구성 요소는 별도의 js 파일에 있습니다.

comp1.js의 comp2.js 당신은뿐만 아니라 서로 구성 요소 컨트롤러를 확장 할 수 있습니다

+0

찾고 계신 정보 [this] (http://stackoverflow.com/a/20230720/6263032)이 무엇입니까? – domyos

+0

불행히도이 대답은 컨트롤러에 관한 것이지 .component()가 아닙니다. – Amine

+0

이것은 구성 요소와 아무 관련이 없습니다. 각도 1.5에서는 구성 요소가 지시문을 작성하는 간단한 방법입니다. components/directive는 ng-controller로 주석을 달고 html-tag 할 수있는 것과 같은 방법으로 컨트롤러를 사용합니다. – domyos

답변

0

을 comp3.js. (에서 연장)

부모 요소 : 다음과 같은 방법을 사용

/** 
* 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, $parentDep) { 

    //Get controllers 
    const $ctrl = this; 
    const $base = $controller('ParentCtrl', {$parentDep}); 

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

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

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

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

을, 기존 메서드를 덮어 쓰거나, 부모 메서드를 호출하는 등의 작업을합니다.

0

단순히 서비스를 사용하여 구성 요소를 공유하고 작성하는 것이 좋습니다. 그런 다음

angular 
    .module('app') 
    .factory('component.utils', function() { 
     return { 
     sharedProp: 'foo', 
     sharedMethod: function() { return 'bar' } 
     } 
    }) 
    // components can all easily use functionality 
    // provided by one (or more) services, w/o 
    // needing a complicated inheritance model. 
    .component('foo', { 
     templateUrl: 'foo.html', 
     controller: [ 
     'component.utils', 
     function(utils) { 
      this.$onInit = function() { 
      this.prop = utils.sharedProp; 
      utils.sharedMethod(); 
      // now do other foo things... 
      } 
     } 
     ] 
    }) 
    .component('bar', { 
     templateUrl: 'foo.html', 
     controller: [ 
     'component.utils', 
     function(utils) { 
      this.$onInit = function() { 
      this.prop = utils.sharedProp; 
      utils.sharedMethod(); 
      // now do other bar things... 
      } 
     } 
     ] 
    }); 

상속이 자리가 등 .extend(), $controller에 대한 걱정의 복잡성을 건너 뛸 수 있지만 상속을 통해 구성을 선호하는 것이 일반적으로 더 나은 솔루션입니다 수 있습니다.