Skip to content

Instantly share code, notes, and snippets.

@btm1
Last active February 22, 2016 09:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save btm1/6802599 to your computer and use it in GitHub Desktop.
Save btm1/6802599 to your computer and use it in GitHub Desktop.
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 : post.id, data-name : post.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) {
elem.attr(k,v.value);
elem.removeAttr('set-attr');
}
} else {
elem.attr(k,v);
elem.removeAttr('set-attr');
}
});
}
}
}
});
@victor-homyakov
Copy link

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