Created
December 5, 2016 17:54
-
-
Save olaferlandsen/5161699df4570ba1a8b6093ed55ad9d5 to your computer and use it in GitHub Desktop.
Set dynamic attributes with angular
This file contains 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('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