javascript - Angular Directive(指令)不会更新与 Controller 的双向绑定(bind)

标签 javascript angularjs angular-directive

我有一个模态指令,当按下按钮时该指令应该变得可见。但是,负责确定与指令双向绑定(bind)的模式是否应该打开的值似乎没有更新。有什么想法吗?

这是指令 JS:

function modalDialogSelect() {
  return {
    restrict: 'AE',
    scope: {
      show: '='
    },
    replace: true,
    transclude: true,
    link: function(scope, element, attrs) {
      scope.dialogStyle = {};
      scope.hideModal = function() {
        scope.show = false;
      };
    },
    templateUrl: "./views/directive_templates/select_modal.html"
  };
 }

指令内部 HTML URL:

<div class='ng-modal' ng-show='show'>
  <div class='ng-modal-overlay' ng-click='hideModal()'></div>
    <div class='ng-modal-dialog' ng-style='dialogStyle'>
      <p>Select New Customer</p>
    </div>
  </div>
</div>

单击并打开模式的按钮:

<button ng-click='selectCustomer = true;'>SELECT/CREATE CUSTOMER</button>

以及我的通用 HTMl 中的 modal-dialog-select 指令

<modal-dialog-select show='selectCustomer'></modal-dialog-select>

有什么想法为什么scope.show没有在我的指令中更新吗?谢谢!

最佳答案

您生成的模态模板存在问题

Error: Template must have exactly one root element. was: 
<div class='ng-modal' ng-show='show'>
  <div class='ng-modal-overlay' ng-click='hideModal()'></div>
  <div class='ng-modal-dialog' ng-style='dialogStyle'>
    <p>Select New Customer</p>
  </div>
        </div>
</div>

删除最后一个 </div> 后一切正常。

var app = angular.module("myApp", []);

app.controller('ParentController', function($scope) {
  $scope.selectCustomer = false;
});

app.directive('modalDialogSelect', function() {
  return {
    restrict: 'AE',
    scope: {
      show: '='
    },
    replace: true,
    transclude: true,
    link: function(scope, element, attrs) {
      scope.dialogStyle = {};
      scope.hideModal = function() {
        scope.show = false;
      };
    },
    templateUrl: "modal.html"
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ParentController"> 

  <p>Flag is: {{selectCustomer}}</p>
  <button ng-click='selectCustomer = !selectCustomer'>SELECT/CREATE CUSTOMER</button>

  <modal-dialog-select show='selectCustomer'></modal-dialog-select>


  <script type="text/ng-template" id="modal.html">
    <div class='ng-modal' ng-show='show'>
      <div class='ng-modal-overlay' ng-click='hideModal()'></div>
      <div class='ng-modal-dialog' ng-style='dialogStyle'>
        <p>Select New Customer</p>
      </div>
    </div>
  </script>
</div>

关于javascript - Angular Directive(指令)不会更新与 Controller 的双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31145809/

相关文章:

javascript - IF 语句并返回到函数的开头

javascript - 内部左侧导航

Angular - 如何从指令访问和替换 innerHTML

angular - Angular中结构指令和属性指令之间的区别?

javascript - Angular 组件不会显示

javascript - 动画显示谷歌地图和谷歌街景的路线

javascript - 在不堆叠多个元素的情况下切换可见性

javascript - 用于更改 backgroundPosition 的动态变量

c# - 如何将字符串数组从 AngularJS 传递到 C# web api?

javascript - 很少有 Angular 服务,仅在常量上有所不同