1

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!

user70192
  • 13,786
  • 51
  • 160
  • 240
  • possible duplicate of [Input autofocus attribute](http://stackoverflow.com/questions/14859266/input-autofocus-attribute) – John Munsch Jun 27 '14 at 13:57
  • I see that. However, I don't like this approach. In my opinion it dirtys up the $scope. With this approach, I have to have a variable for each control. I'm trying to create a directive that allows me to give the ID of a control at the form level. I will then find that control and I'd like to set the autofocus attribute on that control. – user70192 Jun 27 '14 at 14:07
  • firstly, what the reason to add `autofocus` to several elements? Do you want to add it by elements's id or by some jQuery selector? – Yuriy Rozhovetskiy Jun 27 '14 at 14:42
  • I do NOT want several elements to have autofocus. Instead, I want to find an element within the form element and add autofocus to that element. I want to add autofocus to an element by ID. – user70192 Jun 27 '14 at 15:06

2 Answers2

1

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.

KSev
  • 1,859
  • 1
  • 24
  • 23
0

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();
            }
          }
        });
      }
    };
  });
})();

Plunker

Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68