Created
August 20, 2014 18:06
-
-
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.
This file contains hidden or 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
$scope.things = []; | |
$scope.hasChanged = { | |
mySuperAwesomeStuff: false, | |
}; | |
$scope.$watch('things', function () { | |
$scope.hasChanged.mySuperAwesomeStuff = true; | |
}); |
This file contains hidden or 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
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); | |
}); | |
}; | |
} | |
}; | |
}); |
This file contains hidden or 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
<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