AngularJS: сервис компиляции (интерполяции) шаблонов

Нужно было сделать объектов через шаблоны и отдавать дальше, не в AngularJS.
Сделал для этого службу

/**
 * It's for compiling template into html using scope
 */
.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;
		},
		/**
		 * Gets template and interpolates it to html using params
		 * @param {String} url template url
		 * @param {Boolean} throwOnError throw error on load error
		 * @returns {Promise}
		 */
		getTemplateByUrl: function getTemplateByUrl(url, throwOnError)
		{
			return $http.get($sce.getTrustedResourceUrl(url), {cache: $templateCache});
		}
	};
}])

использование:

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);

		marker
			.setPopupContent(parentEl)
			.openPopup();
	});

UPD: обновил, теперь круто.

Gist:
https://gist.github.com/bullgare/d2c1a7ea335fb301afbe

LEAVE A COMMENT