-
-
Save bullgare/d2c1a7ea335fb301afbe to your computer and use it in GitHub Desktop.
Service for compiling and interpolating templates into html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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