[英]How can i put html inside javascript varaible
目前,我有這種骯臟的編碼功能,可以返回HTML。
有沒有更好的方法可以做到這一點。
我很難在其中插入變量,它看起來很臟
function getTemplate (model, id) {
model = "Test";
id = 5;
return '<div>' +
'<button class="btn btn-xs btn-info" title="View"' +
'ng-click="openTab(panes[1], "' + model + '", "' + id + '")">' +
'<span class="glyphicon glyphicon-cog"></span>' +
'</button>' +
'<button class="btn btn-xs btn-info" title="Edit"' +
'ng-click="editModal(model, id)">' +
'<em class="fa fa-pencil"></em>' +
'</button>' +
'<button class="btn btn-xs btn-danger" title="Delete"' +
'ng-click="deleteEntry(id, model)">' +
'<em class="fa fa-trash"></em>' +
'</button>' +
'</div>';
}
編輯:
我正在使用角度UI Grid。 我在列內渲染這些按鈕。 需要Html中的cellTemplate
我很難在其中插入變量,它看起來很臟
使用$ templateRequest,您可以通過模板的URL加載模板,而不必將其嵌入字符串中。 如果模板已經加載,它將從緩存中獲取。
app.controller('MainCtrl', function($scope, $templateRequest, $sce, $compile){
$scope.name = 'World';
$scope.getTemplate = function (model, id) {
// Make sure that no bad URLs are fetched. If you have a static string like in this
// example, you might as well omit the $sce call.
var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
$scope.model = "Test";
$scope.id = 5;
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
$compile($("#my-element").html(template).contents())($scope);
}, function() {
// An error has occurred
});
};
});
請注意,這是手動操作,而在大多數情況下,更可取的方法是定義一個指令,該指令使用templateUrl屬性來獲取模板。
此外,您可以直接綁定變量,因為它們在同一范圍內。
這是演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.