我有一个简单的按钮指令,可以在单击按钮时通知控制器。但是我不明白为什么我需要添加$ scope。$ digest()以便操作更新范围。见代码:
var myModule = angular.module("myModule", []);
myModule.directive("myDirective", function() {
return {
restrict: "A",
scope: {
action: "&"
},
link: function(scope, element, attrs) {
element.bind("click", function() {
scope.action();
});
}
};
});
myModule.controller("TestCtrl", function($scope) {
$scope.divShow = false;
$scope.buttonClick = function() {
$scope.divShow = !$scope.divShow;
// why is this needed?
$scope.$digest();
}
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule">
<div ng-controller="TestCtrl">
<button my-directive action="buttonClick()">Click</button>
<div ng-show="divShow">
Div is shown
</div>
</div>
</body>
</html>
这是jsfiddle
答案 0 :(得分:1)
您不应该自己运行摘要周期(请参阅AngularJS docs),您可以在范围内运行该功能。$ evalAsync / scope。$ apply / $ timeout(*)回调,因为scope.action()
代码在angular的“外部”执行(它在普通的JS处理程序中):
link: function(scope, element, attrs) {
element.bind("click", function() {
scope.$evalAsync(function(){
scope.action();
});
});
}
**(*)哪一个“最佳”使用超出了本答案的范围:**