Skip to content

Instantly share code, notes, and snippets.

@olaferlandsen
Created December 5, 2016 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olaferlandsen/5161699df4570ba1a8b6093ed55ad9d5 to your computer and use it in GitHub Desktop.
Save olaferlandsen/5161699df4570ba1a8b6093ed55ad9d5 to your computer and use it in GitHub Desktop.
Set dynamic attributes with angular
angular.module('olaferlandsen', [])
/**
* Example of usage:
* <input type="element" ng-attrs='{"my-own-attr" : "value", "max": 10, "min":0}'>
*/
.directive('ngAttributes', function($injector, $compile) {
return function (scope, element, attrs) {
var ngAttributes = attrs.ngAttributes;
if (typeof ngAttributes== 'string') ngAttributes = ngAttributes.replace(/(^\s+|\s+$)/ig, '')
if (ngAttributes.length == 0) return;
ngAttributes = angular.fromJson(ngAttributes);
angular.forEach(ngAttributes, function (value, attribute) {
attr = attribute.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase()
element.attr(attr, value);
});
// Remove ngAttributes to prevent recursive call
element.removeAttr('ng-attributes');
$compile(element)(scope);
};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment