Javascript 如何从外部编译动态模板?
我想通过AJAX加载动态HTML内容,然后对其进行编译,因为它包含角度指令 我使用的方法有助于使用angular,但不在angular控制器或指令的范围内:Javascript 如何从外部编译动态模板?,javascript,angularjs,Javascript,Angularjs,我想通过AJAX加载动态HTML内容,然后对其进行编译,因为它包含角度指令 我使用的方法有助于使用angular,但不在angular控制器或指令的范围内: var AngularHelper = (function () { var AngularHelper = function () { }; /** * ApplicationName : Default application name for the helper */ var defau
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>
AngularJS试验
$(文档).ready(函数(){
$.get(”http://fuiba.com/test/index.html,函数(数据){
$(“#结果”).html(数据);
编译(“$(“#结果”)”,数据);
});
});
但是我得到了这个错误(见下图):
$targetDom.html不是函数
您需要在
angularheloper.Compile
函数中传递DOM元素而不是字符串作为第一个参数
所以
angularheloper.Compile($(“#结果”),数据代码>
不是
angularheloper.Compile(“$(“#结果”)”,数据代码>在这一行angularheloper.Compile(“$(“#结果”)”,数据)
您正在为参数$targetDom
传递字符串('$(“#result”)
),但稍后在函数中,您通过调用.html
函数来处理它,就像处理jQuery对象一样。字符串类当然没有这种方法。@RytisAlekna感谢您和MiTa,问题已经解决了,但我得到了另一个错误。看这个。非常感谢@MiTa!!问题已解决,但我遇到另一个错误:模块“MyApp”不可用!您要么拼错了模块名,要么忘记加载它。如果注册一个模块,请确保将依赖项指定为第二个参数。
查看第41行angular.module('MyApp')
您刚刚获得了这个模块,但您必须创建它angular.module('MyApp',[])
我不知道为什么这个angularheloper类对其他人而不是我来说工作得很好。我遇到另一个错误:$targetDom.html(…)。作用域不是函数。我会尽力解决的!非常感谢。