Create a gist now

Instantly share code, notes, and snippets.

@btm1 /set-attr
Last active Feb 22, 2016

Set attribute is a directive that takes an object and evaluates each property where the key is the attribute you want to set and the value is the value for that attribute i.e. set-attr="{ data-id :, data-name : }" Additionally if the value for each key can also be an object with two properties "condition" and "value" where cond…
angular.module('setAttr',[]).directive('setAttr', function() {
return {
restrict: 'A',
priority: 100,
link: function(scope,elem,attrs) {
if(attrs.setAttr.indexOf('{') != -1 && attrs.setAttr.indexOf('}') != -1) {
//you could just angular.isObject(scope.$eval(attrs.setAttr)) for the above but I needed it this way
var data = scope.$eval(attrs.setAttr);
angular.forEach(data, function(v,k){
if(angular.isObject(v)) {
if(v.value && v.condition) {
} else {

Should elem.removeAttr('set-attr'); be called only once outside of forEach loop?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment