Reputation: 14204
I'm working on an AngularJS app. I'm trying to add the autofocus attribute to an element at runtime. The reason I want to do this is so I can set this attribute on one of several elements. How do you add an HTML attribute to an element via an AngularJS directive?
Thank you!
Upvotes: 1
Views: 912
Reputation: 1879
You can use the $set method on the $compile.directive.Attributes
object. See the documentation here. This will create a new attribute which AngularJS will recognize. Remember to use the normalized (camelCase) version of the attribute. You can do it in the link function of your directive.
Upvotes: 1
Reputation: 22448
That's directive:
(function(){
angular.module('ng').directive('dynamicAutoFocus', function(){
return {
restrict: 'A',
link: function(scope, element, attrs){
scope.$watch(attrs.dynamicAutoFocus, function(id){
if(angular.isDefined(id)){
var target = document.getElementById(id);
if(target){
target.focus();
}
}
});
}
};
});
})();
Upvotes: 0