Last active
February 22, 2016 09:59
-
-
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…
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
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'); | |
} | |
}); | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should
elem.removeAttr('set-attr');
be called only once outside offorEach
loop?