请考虑以下使用Controller As syntax的示例:
<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”语法时,你会怎么做?
答案 0 :(得分:4)
由于控制器被定义为 我的,您需要使用:
scope.my.message = 'World';
scope.$apply();