我有以下 html:
<div class="modal-dialog" ng-controller="modal-ctrl" ng-show="showModal" execute-on-esc>
Angular.js 应用程序:
app.controller('modal-ctrl', function($scope) {
$scope.showModal = true;
});
app.directive('executeOnEsc', function ($document) {
return {
restrict: 'A',
link: function (scope) {
return $document.bind('keydown', function(event) {
event.which === 27? scope.showModal = false : false;
});
}
}
});
一切正常,$scope.showModal 更改为 false,但 ng-show 不响应此更改。为什么? Console.log 显示 $scope.showModal 发生变化。 问题出在哪里?
最佳答案
return $document.bind('keydown', function(event) {
event.which === 27? scope.showModal = false :
});
您正在创建一个事件监听器,该监听器在 Angular 摘要周期之外执行。因此,您必须告诉 Angular 开始一个新的摘要周期才能接受更改。您可以使用scope.$apply为此:
return $document.bind('keydown', function(event) {
scope.$apply(function(){
event.which === 27? scope.showModal = false :
});
});
演示
var app = angular.module("app", []);
app.controller('modal-ctrl', function($scope) {
$scope.showModal = true;
});
app.directive('executeOnEsc', function($document) {
return {
restrict: 'A',
link: function(scope) {
return $document.bind('keydown', function(event) {
scope.$apply(function() {
event.which === 27 ? scope.showModal = false : false;
});
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div class="modal-dialog" ng-controller="modal-ctrl" ng-show="showModal" execute-on-esc>
My Modal
</div>
</div>
关于javascript - Angular.js ng-show 和指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555551/