Skip to content

Instantly share code, notes, and snippets.

@btm1
Created October 2, 2013 23:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save btm1/6802312 to your computer and use it in GitHub Desktop.
Save btm1/6802312 to your computer and use it in GitHub Desktop.
set-if will conditionally show or hide elements in the DOM once and will not apply a $watch listener. An additional attribute (wait-for) can be applied to the element to wait for data to be populated before evaluating the if statement i.e. <div set-if="should.behere" wait-for="should"></div>
angular.module('setIf',[]).directive('setIf',function () {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, linker) {
return function (scope, iterStartElement, attr) {
if(attr.waitFor) {
var wait = scope.$watch(attr.waitFor,function(nv,ov){
if(nv) {
build();
wait();
}
});
} else {
build();
}
function build() {
iterStartElement[0].doNotMove = true;
var expression = attr.setIf;
var value = scope.$eval(expression);
if (value) {
linker(scope, function (clone) {
iterStartElement.after(clone);
clone.removeAttr('set-if');
clone.removeAttr('wait-for');
});
}
}
};
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment