我正在尝试创建一个与这篇文章非常相似的模式弹出切换:http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/
但是,我遇到了问题,因为在我的代码中,ng-click 代码只运行一次,然后在下一次停止工作。我可以调出模态对话框,但除非刷新页面,否则无法复制它。
代码如下:
/scripts/controllers/.navjs
'use strict';
app.controller('NavCtrl', function ($scope) {
$scope.modalShown = false;
$scope.toggleModal = function() {
$scope.modalShown = !$scope.modalShown;
};
});
/views/nav.html
<div>
...
<li><a ng-click="toggleModal()">Settings</a></li>
...
</div>
<modal show='modalShown' width='750px' height='60%'>
<p>Modal Content Goes here<p>
</modal>
/scripts/directives/modal.js
'use strict';
app.directive('modal', function() {
return {
restrict: 'E',
scope: {
show: '='
},
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width) {
scope.dialogStyle.width = attrs.width;
}
if (attrs.height) {
scope.dialogStyle.height = attrs.height;
}
scope.hideModal = function() {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
toggleModal 函数似乎在第一次单击后停止工作。有什么想法吗?
更新
这是我的 index.html 的样子:
<!-- Add your site or application content here -->
<div ng-controller='NavCtrl' ng-include="'views/nav.html'"></div>
<div ng-view="container" id="main-container"></div>
当我将 ng-controller='NavCtrl' 移动到我的 ng-view 下面时,切换工作,但导航栏出现在页面的最底部......
最佳答案
似乎问题是 Angular JS 范围隔离。当您使用 ngInclude 指令时,您已经创建了独立的范围。由于您只使用 bool 变量,因此无法从独立范围更改它。必须使用对象。
就用
$scope.modalShown = {
value: false
}
在 html 中
... show='modalShown.value' ...
关于javascript - ng-click 在第一次点击后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111217/