我有一個字符串變量舉行的AngularJS模板,如:AngularJS模板如何呈現在變量中?
var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';
以供參考,該字符串已經從外部API(因此它在一個變量被關押返回,而不是一個物理文件)。
我該如何去渲染這個模板,使用Angular的模板引擎,並正確綁定表達式如{{ title }}
和{{ intro }}
?
我有一個字符串變量舉行的AngularJS模板,如:AngularJS模板如何呈現在變量中?
var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';
以供參考,該字符串已經從外部API(因此它在一個變量被關押返回,而不是一個物理文件)。
我該如何去渲染這個模板,使用Angular的模板引擎,並正確綁定表達式如{{ title }}
和{{ intro }}
?
與範圍Compile and Link它:
var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';
$scope.title = 'test title';
$scope.intro = 'test intro';
var compiledAndLinked = $compile(templateContent)($scope);
編輯:
這裏的和例如:
HTML:
<div ng-app='app'>
<div direct>
</div>
</div>
JS:
var app = angular.module('app',[]);
app.directive('direct', function($compile){
return {
restrict: 'A',
replace: 'true',
template: '<div>\
<input type="text" ng-model="inputHtml" />\
<button ng-click="createHtmlInputText()">Create Sample Html</button>\
<br/>\
<button ng-click="generateHtml()">Generate Html And Append</button>\
</div>',
link: function (scope, element, attrs) {
scope.title = 'test title'
scope.generateHtml = function(){
var compiled = $compile('<br/>' + scope.inputHtml)(scope);
element.append(compiled);
}
scope.createHtmlInputText = function(){
scope.inputHtml = '<span style="color:red">{{title}}</span>';
}
}
};
});
上述
這可能是工作,也許......
var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', templateContent);
});
....
<div ng-include src=" 'templateId.html' "></div>
.... 我可能會使用NG-包括錯誤,請參閱文檔:https://docs.angularjs.org/api/ng/directive/ngInclude
已更新 我很好奇,所以做了一個plunkr。這裏
http://plnkr.co/edit/xApbUzlCQkMXlI4zmFBm?p=preview
它的工作=)
<h4>first</h4>
<div ng-include src=" 'cached.html' "></div>
<br/>
<h4>second</h4>
<div ng-include=" 'cached.html' "></div>
感謝阿米爾 - 什麼會成爲你如何'compiledAndLinked'添加到DOM /頁的建議嗎? – coatesap 2014-09-04 16:08:35
我現在只添加了一個示例(帶有編輯)。對不起,我沒有這樣做 - 我沒有時間.. – 2014-09-05 14:32:17