我正在使用jQuery和AngularJS开发一个Ajax应用程序.

When I update content (which contains AngularJS bindings) of a div using jQuery's html function, the AngularJS bindings doesn't work.

Following is code of what I am trying to do:

$(document).ready(function() {
  $("#refreshButton").click(function() {
    $("#dynamicContent").html("<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>")
  });
});
</style><script src="http://docs.angularjs.org/angular-1.0.1.min.js"></script><style>.ng-invalid {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
  <div id='dynamicContent'>
    <button ng-click="count = count + 1" ng-init="count=0">
        Increment
      </button>
    <span>count: {{count}} </span>
  </div>


  <button id='refreshButton'>
    Refresh
  </button>
</div>

I have dynamic content inside a div with the ID #dynamicContent, and I have a refresh button that would update contents of this div when refresh is clicked. Increment works as expected if I don't refresh the content, but after I refresh, the AngularJS binding stops working.

This may not be valid in AngularJS, but I initially built application with jQuery and started using AngularJS later on so I can't migrate everything to AngularJS. Any help with getting this working in AngularJS is greatly appreciated.

推荐答案

在将HTML字符串插入到DOM之前,需要对其调用$compile,以便ANGLE有机会执行绑定.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

显然,必须将$compile注入控制器才能工作.

Read more in the $compile documentation.

Jquery相关问答推荐

JQuery UI-AutoComplete未显示下拉菜单

如何向父元素添加类?

从文本区域获取值

jQuery 时间 Select 器

与其他 Javascript 框架相比,为什么 jQuery 被如此广泛地采用?

确定元素是否是其父元素的最后一个子元素

将变量传递给jQuery AJAX成功回调中的函数

jQuery Mobile:动态添加内容的标记增强

如何使用 jQuery 重置 jquery Select 的 Select 选项?

谷歌图表重绘/zoom 窗口调整大小

如何使用 jquery 更改 onclick 事件?

将返回的 JSON 对象属性转换为(较低的第一个)camelCase

未捕获的 TypeError:data.push 不是函数

如何使用 jQuery 在悬停时显示工具提示消息?

如何隐藏 Twitter Bootstrap 下拉菜单

在 Firefox 上开发的 Javascript 在 IE 上失败的典型原因是什么?

只绑定一次事件

自调用函数前的分号?

'touchstart' 事件是否有与点击事件相同的 e.PageX 位置?

在 Javascript/jQuery 中,(e) 是什么意思?