AngularJS"验证"指令不能正确编译

时间:2014-11-12 06:13:29

标签: javascript html angularjs directive

我正在尝试编写一个指令,当添加到按钮元素周围的包装器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

]

1 个答案:

答案 0 :(得分:0)

bind()是一个jqLit​​e方法(如果你在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