ng-click不适用于由指令动态添加的元素

时间:2014-02-14 20:38:26

标签: angularjs twitter-bootstrap

我有一个指令初始化一个将显示计算器的bootstrap popover。计算器弹出窗口有一个计算按钮,它有一个ng-click,但是我无法触发click事件。

经过一番研究;我想我需要使用$ compile服务,但我似乎无法弄清楚如何在这种情况下使用它。

define [], ()->
 ($filter, $compile) ->
   ddo = 
    require: "ngModel"
    restrict: "A"
    scope: true
    priority: 10
    controller: ['$scope', '$element', '$q', ($scope, $element, $q)->

     $scope.calculate = ()->
      console.log "calc"

  ]
  link: (scope, elem, attrs, ngModel) ->
    elem.wrap("<div class=\"input-group\"></div>")
    pre = $("<span class=\"input-group-addon\" style=\"font-size:0.8em;\">$</i></span>")
    post = $("<div data-toggle=\"popover\" class=\"input-group-addon pop\"><i class=\"      fa fa-github-alt\" style=\"font-size:0.8em;\"></i></div>")
    elem.before(pre)
    if attrs.showCalc == "true"
      elem.after(post)

    $(".pop").popover(
      {
        html: true, 
        title: 'Calculator', 
        content: "Expression:<input ng-model='data.expression' type='text'></input><br>
                  Result:<input ng-model='data.result' type='text'></input>
                  <div ng-click='calculate()' style='margin-top: 5px;' class='btn btn-default btn-calculate'>Calculate</div>
                  <div ng-click='applyValue()' style='margin-top: 5px;' class='btn btn-default btn-apply'>Apply</div>"
        })

1 个答案:

答案 0 :(得分:0)

查看source code of popover,似乎如果content是HTML对象,那么即使此行为未记录,它们也会将其附加到DOM并保留js-events。因此,这应该起作用(至少在理论上):

$(".pop").popover(
  {
    html: true, 
    title: 'Calculator', 
    content: $compile("Expression:<input ng-model='data.expression' type='text'></input><br>
              Result:<input ng-model='data.result' type='text'></input>
              <div ng-click='calculate()' style='margin-top: 5px;' class='btn btn-default btn-calculate'>Calculate</div>
              <div ng-click='applyValue()' style='margin-top: 5px;' class='btn btn-default btn-apply'>Apply</div>")
             (scope)
    })