Skip to content

Instantly share code, notes, and snippets.

@bullgare
Last active August 29, 2015 14:01
Show Gist options
  • Save bullgare/d2c1a7ea335fb301afbe to your computer and use it in GitHub Desktop.
Save bullgare/d2c1a7ea335fb301afbe to your computer and use it in GitHub Desktop.
Service for compiling and interpolating templates into html
Compiler.interpolateByUrl(tplPopupAddressUrl, {item: item})
.then(function (html) {
var newScope = $scope.$new();
newScope.routeTo = function routeTo()
{
alert(123455);
};
var parentEl = Compiler.compile(html, newScope, true);
item.marker
.bindPopup(parentEl)
.openPopup();
});
.factory('Compiler', [
'$rootScope',
'$compile',
'$interpolate',
'$http',
'$sce',
'$templateCache',
'$q',
function Compiler($rootScope, $compile, $interpolate, $http, $sce, $templateCache, $q) {
return {
/**
* Compiles given string with html in it into either list of elements or div with compiled elements as children
* @param {String} html
* @param {Object} scope $scope
* @param {Boolean} asHtml if html needed
* @returns {Array|HTMLElement}
*/
compile: function compile(html, scope, asHtml) {
var compiledElments = $compile(angular.element(html))(scope);
if (! asHtml) {
return compiledElments;
}
var parentEl = document.createElement('div');
angular.forEach(compiledElments, function (el) {
parentEl.appendChild(el);
});
return parentEl;
},
/**
* Interpolates template to html using params
* @param {String} html template
* @param {Object} params
* @returns {String}
*/
interpolate: function interpolate(html, params)
{
return $interpolate(html || '')(params || {});
},
/**
* Gets template and interpolates it to html using params
* @param {String} url template url
* @param {Object} params
* @param {Boolean} throwOnError throw error on load error
* @returns {Promise}
*/
interpolateByUrl: function interpolate(url, params, throwOnError)
{
var deferred = $q.defer(),
me = this;
$http.get($sce.getTrustedResourceUrl(url), {cache: $templateCache})
.success(function (content) {
var str = me.interpolate(content, params);
deferred.resolve(str);
})
.error(function (response) {
var msg = 'Failed to load template: ' + url;
deferred.reject(msg);
if (throwOnError) {
throw Error(msg);
}
});
return deferred.promise;
}
};
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment