Skip to content

Instantly share code, notes, and snippets.

@adambarthelson
Created August 20, 2014 18:06
Show Gist options
  • Save adambarthelson/8f1daebffbbd616a0f04 to your computer and use it in GitHub Desktop.
Save adambarthelson/8f1daebffbbd616a0f04 to your computer and use it in GitHub Desktop.
Directive to recompile a template if data does change and the one-time binding doesn't do this for you.
$scope.things = [];
$scope.hasChanged = {
mySuperAwesomeStuff: false,
};
$scope.$watch('things', function () {
$scope.hasChanged.mySuperAwesomeStuff = true;
});
app.directive('recompileMeWhen', function($compile, $parse) {
'use strict';
function getElementAsHtml(el) {
// http://jsperf.com/jquery-div-vs-span
return angular.element('<a></a>').append(el.clone()).html();
}
return {
compile: function(el) {
var template = getElementAsHtml(el);
return function link(scope, $el, attrs) {
scope.$watch(attrs.recompileMeWhen, function(val) {
if (!val || val === 'false') {
return;
}
// recompile
var newEl = $compile(template)(scope);
$el.replaceWith(newEl);
$el = newEl;
// reset recompileMeWhen to false
$parse(attrs.recompileMeWhen).assign(scope, false);
});
};
}
};
});
<div recompile-me-when="hasChanged.mySuperAwesomeStuff">
<some-super-awesome-directive repeat='thing in things'/>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment