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!

4
  • possible duplicate of Input autofocus attribute Commented Jun 27, 2014 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. Commented Jun 27, 2014 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? Commented Jun 27, 2014 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. Commented Jun 27, 2014 at 15:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.