2017-02-24 2 views
1

나는 내 Angularjs 프로젝트에서 보통 controllerAs 구문을 사용합니다. 이것은 템플릿에서 더 명확해질 것입니다.
그러나 현재 웹 응용 프로그램에서, 나는 다음과 같은 문제로 온 :angularjs : templateAs에서 고립 된 스코프 지시어의 속성에 접근하기 위해 controllerAs를 사용하는 방법

function FirstCtrl() { 
    this.name = 'First Controller'; 
} 

function fooDirective() { 
    return { 
     scope: { 
      testData:'=' 
     }, 
     name: 'ctrl', 
     controller: 'FirstCtrl', 
     controllerAs: 'foo', 
     template: '<div>{{ foo.name }} {{testData}} {{foo.testData}}</div>', 
     link: function ($scope, $element, $attrs, $ctrl) { 
      console.log($ctrl.name); 
     } 
    }; 
} 

angular 
    .module('app', []) 
    .directive('fooDirective', fooDirective) 
    .controller('FirstCtrl', FirstCtrl); 

하는 HTML 부분은 다음과 같습니다 :

<div ng-app="app"> 
    <foo-directive test-data="'newdata'"></foo-directive> 
</div> 

및 라이브 데모는 여기에 있습니다 :
https://jsfiddle.net/baoqger/rbp1wyfa/

그리고 템플릿 부분에 혼란스러운 점이 있습니다 :

template: '<div>{{ foo.name }} {{testData}} {{foo.testData}}</div>', 

{{testData}}은 잘 작동 할 수 있습니다. 그러나 {{foo.testData}} 수 없습니다. 문제를 해결하는 방법 그래서 난 컨트롤러 개체에서 격리 된 범위 개체의 속성에 액세스 할 수 있습니다.

답변

1

당신은 당신의 지침 정의에 bindToController: true를 추가 할 :

function fooDirective() { 
    return { 
     scope: { 
      testData:'=' 
     }, 
     name: 'ctrl', 
     controller: 'FirstCtrl', 
     controllerAs: 'foo', 
     bindToController: true, 
     template: '<div>{{ foo.name }} {{testData}} {{foo.testData}}</div>', 
     link: function ($scope, $element, $attrs, $ctrl) { 
      console.log($ctrl.name); 
     } 
    }; 
} 

적용 문서 (당신이 그들의 부동 메뉴/헤더의 BC 조금을 스크롤해야 할주의) here입니다.

+0

감사합니다. 그것은 잘 작동합니다. 나는 그런 매개 변수를 놓쳤습니다 ... 감사합니다. –

+0

당신은 환영합니다. 지시어 정의는 복잡하고 종류가 다양 할 수 있습니다. 문서에서 물건을 놓치기 쉽습니다. 도와 줘서 기뻐요! –

관련 문제