首次单击后,ng-click停止工作

时间:2014-06-08 21:51:24

标签: 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-view下面移动ng-controller ='NavCtrl'时,切换工作,但导航栏出现在页面的最底部......

1 个答案:

答案 0 :(得分:0)

似乎问题是角度JS范围隔离。使用ngInclude指令时,您已创建了隔离范围。而且,由于您只使用bool变量,因此无法从隔离范围更改它。必须使用对象。

只需使用

 $scope.modalShown = {
    value: false
 } 

in html

... show='modalShown.value' ...
相关问题