【发布时间】:2016-03-29 22:09:57
【问题描述】:
我想通过 AJAX 加载动态 HTML 内容,然后编译它,因为它包含 angular 指令。
我有 this class 使用有助于使用 angular 的方法,而不是在 angular 控制器或指令的范围内:
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "MyApp";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
然后我在我的 jQuery 成功的 ajax 请求之后使用它:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Test</title>
</head>
<body>
<div id="contents"><!-- content --></div>
<script src="js/angular.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get( "http://fuiba.com/test/index.html", function( data ) {
$("#result").html(data);
AngularHelper.Compile('$("#result")', data);
});
});
</script>
</body>
</html>
但我收到此错误(请参阅此codepen):
$targetDom.html 不是函数
【问题讨论】:
-
在这一行
AngularHelper.Compile('$("#result")', data);中,您正在为参数$targetDom传递字符串('$("#result")'),但稍后在函数中,您可以通过调用.html函数来处理它,就像处理jQuery 对象一样。 String 类当然没有这种方法。 -
@RytisAlekna 感谢您和 MiTa,问题已解决,但我遇到了另一个错误。看到这个codepen。
标签: javascript angularjs