Reputation: 6831
Currently I have this dirty way of coding function which returns HTML.
Is there any better way i can do it.
I am having hard time in inserting variables inside it and it looks very dirty
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>';
}
EDIT:
I am using angular UI Grid . I am rendering these buttons inside column. which needs cellTemplate in Html
Upvotes: 1
Views: 92
Reputation: 7425
I am having hard time in inserting variables inside it and it looks very dirty
Using $templateRequest, you can load a template by it’s URL without having to embed it into a string. If the template is already loaded, it will be taken from the cache.
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
});
};
});
Be aware that this is the manual way to do it, and whereas in most cases the preferrable way would be to define a directive that fetches the template using the templateUrl property.
Further, you may bind the variables straightaway since they'd be in the same scope.
Here's the demo
Upvotes: 1