0

ディレクティブを使用する簡単な例を次に示します (公式ガイドから引用) - JSFiddle

<div ng-controller="Controller">
  <my-customer></my-customer>
</div>


angular.module('my-module', [])
.controller('Controller', function($scope) {
     $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
 })
.directive('myCustomer', function() {
     return {
        restrict: 'E',
        template: 'Name: {{vojta.name}} Address: {{vojta.address}}'
     }
 });

上記のディレクティブは、その親コン​​トローラーと同じスコープを持ちます。コントローラーと構文で同じことを行うにはどうすればよいですか?

分離されたスコープでこれを行うことは可能ですが、ディレクティブ用に別のスコープを作成しないソリューションを探しています。それは単に可能ですか?

controllerAsbindToController、およびrequire: '^ngController'からすべてを試しましたが、成功しませんでした。

4

1 に答える 1

1

構文については、コントローラーで次のようcontrollerAsに参照を持つ ViewModel オブジェクトを作成します。this

var vm = this;
vm.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; //your object

テンプレートでは、次のように を使用asしてコントローラーにエイリアスを与える必要があります。

<div ng-controller="Controller as ctrl"> //now inside this scope use 'ctrl' which acts as the 'scope' of the controller.
  <my-customer></my-customer>
</div>

あなたのディレクティブで:

template: 'Name: {{ctrl.vojta.name}} Address: {{ctrl.vojta.address}}' //notice the use of 'ctrl'

ここで働くフィドル

于 2015-10-25T11:49:11.250 に答える