2017-02-24 2 views
1

私は通常、AngularjsプロジェクトでcontrollerAsという構文を使用しています。
しかし、現在のWebアプリケーションでは、私は次のような問題になった: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/

私の混乱する点はテンプレート部分にあります:

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

あなたは歓迎です - 指示の定義は複雑なものにすることができます。助けてうれしい! –

関連する問題