javascript - ng-click 在第一次点击后停止工作

标签 javascript angularjs

我正在尝试创建一个与这篇文章非常相似的模式弹出切换: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/

相关文章:

javascript - 在浏览器控制台与小书签中运行 JavaScript

javascript - 是否可以缓存整个网站,包括开始 html 页面和在没有互联网连接的情况下启动?

javascript - AngularJS:如何在单击时将事件类设置为列表项?三元法

javascript - 当在表单上按下提交时如何调用不同的 get 函数; Angular

javascript - 多个父子作用域事件触发问题

html - 将焦点状态添加到具有嵌入式链接的容器

javascript - Openshift不会运行nodejs应用程序

javascript - 奇怪的 map 行为

javascript - 如何删除 jQuery 中 AJAX 调用后添加的元素?

twitter-bootstrap - 如何从 Angular Bootstrap 模态调用函数(使用 angular-strap)?