1

ライブデモ

Controller As 構文を使用する次の例を考えてみましょう。

<body ng-app="myApp" ng-controller="MyCtrl as my">
  <div>
    {{ my.message }}
  </div>
  <button my-directive>
    Click me 
  </button>
</body> 
var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function() {
  this.message = 'Hello';
});

myApp.directive('myDirective', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        // Change 'message' here
      });
    }
  };
});

messageディレクティブからコントローラーを設定するにはどうすればよいですか?

「Controller As」構文がなければ、次のようにします: (DEMO)

scope.message = 'World';
scope.$apply();

しかし、「Controller As」構文を使用する場合、これをどのように行うのでしょうか?

4

1 に答える 1

4

コントローラーはmyとして 定義されているため、次を使用する必要があります。

scope.my.message = 'World';
scope.$apply();
于 2013-07-08T11:15:50.353 に答える