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

由于控制器被定义 我的你需要使用:

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