如果您对新元素使用片段(例如 $("<" + "div>").appendTo("body")),则对 JQuery prepend/append 方法使用如下包装器可以避免更改元素- 添加代码:
// run angular-compile command on new content
// (also works for prependTo/appendTo, since they use these methods internally)
var oldPrepend = $.fn.prepend;
$.fn.prepend = function()
{
var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment";
var result = oldPrepend.apply(this, arguments);
if (isFragment)
AngularCompile(arguments[0]);
return result;
};
var oldAppend = $.fn.append;
$.fn.append = function()
{
var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment";
var result = oldAppend.apply(this, arguments);
if (isFragment)
AngularCompile(arguments[0]);
return result;
};
function AngularCompile(root)
{
var injector = angular.element($('[ng-app]')[0]).injector();
var $compile = injector.get('$compile');
var $rootScope = injector.get('$rootScope');
var result = $compile(root)($rootScope);
$rootScope.$digest();
return result;
}