AngularJS”;验证“;赢得指令't正确编译

AngularJS "Verify" Directive Won't Compile Correctly

本文关键字:编译 验证 AngularJS 指令      更新时间:2023-09-26

我正在尝试编写一个指令,当将该指令添加到按钮元素周围的包装器div中时,将为调用给定操作添加一个验证步骤。如果用户点击"危险"按钮,该按钮将消失,取而代之的是一个内部带有复选标记的红色按钮。当他们点击复选标记时,操作被调用,按钮返回到正常状态。

目前,我的指令遇到以下问题:

  • 单击原始按钮不会显示"验证"按钮,即使scope.verify发生更改
  • 出于测试目的,将scope.verify默认设置为true后,单击"验证"按钮不会调用预期操作

HTML

<div verify>
  <label class="btn btn-default" data-click="resetFilters()">Clear Filters</label>
</div>

角度

angular.module("App").directive "verify", ["$compile",
  ($compile) ->
    directive = {}
    # This directive should be an attribute
    directive.restrict = "A"
    # We do not want to replace any HTML
    directive.replace = false
    # Skip the compilation of other directives
    directive.terminal = true
    # Compile this directive first
    directive.priority = 1001
    directive.link = (scope, element, attrs) ->
      # Remove verify attribute to prevent infinite compile loop
      element.removeAttr "verify"
      element.removeAttr "data-verify"
      # Select the element under the "verify" div, store the "click"
      # function and remove it from the element
      first = angular.element(element.children()[0])
      clickAction = first.attr "click" || first.attr "data-click"
      first.removeAttr "click"
      first.removeAttr "data-click"
      # Create a new element from the first one. This will become the
      # verify button
      second = first.clone()
      # Add the new element to the DOM
      element.append second
      # Add some custom ngShow / ngHide animation classes
      first.addClass "fader-down"
      second.addClass "fader-up"
      # Specify when each element should show / hide
      first.attr "ng-hide", "verify"
      second.attr "ng-show", "verify"
      # Design the verify button
      second.html "<span class='"glyphicon glyphicon-ok'"</span>"
      second.addClass "btn-danger"
      # Initially, only the original button should be visible
      scope.verify = false
      # When the user clicks on the original button, hide it and show
      # the verify button
      first.bind "click", ->
        scope.verify = true
      # When the user clicks on the second element, the "verify"
      # button, evaluate the specified "click" action. Hide the verify
      # button and show the original button
      second.bind "click", ->
        scope.$eval clickAction
        scope.verify = false
      # Compile the element
      $compile(element)(scope)
      # $compile(element.contents())(scope) # This doesn't work either
    return directive
]

bind()是一个jqLite方法(如果在Angular之前加载jQuery,则为jQuery方法),不会触发摘要循环。您必须通过将其包装在对scope.$apply():的调用中来手动触发它

first.bind('click', function () {
  scope.$apply(function () {
    scope.verify = true;
  });
});

和:

second.bind('click', function() {
  scope.$apply(function() {
    scope.$eval(clickAction);
    scope.verify = false;
  });
});

演示:http://plnkr.co/edit/57X7IBcxafkN2U6W5IhE?p=preview