考虑以下使用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”语法时,你会怎么做呢?