Skip to content

Instantly share code, notes, and snippets.

@rpocklin
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpocklin/fb17aa0c26fef85ef0ee to your computer and use it in GitHub Desktop.
Save rpocklin/fb17aa0c26fef85ef0ee to your computer and use it in GitHub Desktop.
Angular directive which permits re-use for content referring to scope variables.
'use strict';
/**
* An ng-include replacement which transparently inherits the parent scope and also allows local customisation of variables
* within the snippet.
*
* Designed to use $templateCache (in production) and fallback to an AJAX request (for dev-mode) to load view templates.
*
* Use as below (can customise variables used in the snippet via ng-init):
* <div include="'users/_password_confirmation_input.html'" ng-init="placeholder = 'Re-enter Password'"></div>
*
*/
angular.module('yourapp').directive('include', function($http, $templateCache, $compile) {
return {
scope: true,
priority: 450, // overrides ng-include's scope priority
restrict: 'EA',
replace: true,
link: function(scope, el, attr) {
var templatePath = attr.include;
var buildTemplate = function(template) {
var contents = el.html(template).contents();
$compile(contents)(scope);
};
templatePath = templatePath.substring(1, templatePath.length - 1); // trim angularjs quotes off string
var template = $templateCache.get(templatePath);
if (template) {
buildTemplate(template);
return;
}
$http.get(templatePath, {}).success(function(template) {
$templateCache.put(templatePath, template);
buildTemplate(template);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment