Skip to content

Instantly share code, notes, and snippets.

@Arwid
Last active August 29, 2015 14:27
Show Gist options
  • Save Arwid/d8d637bdec0433ee16f6 to your computer and use it in GitHub Desktop.
Save Arwid/d8d637bdec0433ee16f6 to your computer and use it in GitHub Desktop.
AngularJS RecompileOn Directive
// Forked from: https://medium.com/@kentcdodds/angularjs-one-time-bindings-and-recompiling-templates-9857b2cead01
/* global angular */
var directives = angular.module('directives');
directives.directive('recompileOn', ['$parse', function($parse) {
'use strict';
return {
transclude: true,
link: function link(scope, $el, attrs, ctrls, transclude) {
var previousElements;
// compile();
function compile() {
transclude(scope, function(clone, clonedScope) {
// transclude creates a clone containing all children elements;
// as we assign the current scope as first parameter, the clonedScope is the same
previousElements = clone;
$el.append(clone);
});
}
function recompile() {
if (previousElements) {
previousElements.remove();
previousElements = null;
$el.empty();
}
compile();
}
scope.$on(attrs.recompileOn, function(_new, _old) {
console.log("recompileOn",attrs.recompileOn);
var useBoolean = attrs.hasOwnProperty('useBoolean');
if ((useBoolean && (!_new || _new === 'false')) || (!useBoolean && (!_new || _new === _old))) {
return;
}
// reset kcdRecompile to false if we're using a boolean
if (useBoolean) {
$parse(attrs.recompileOn).assign(scope, false);
}
recompile();
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment