user70192
user70192

Reputation: 14204

AngularJS - Add attribute at runtime

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

Answers (2)

KSev
KSev

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

IUnknown
IUnknown

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

Plunker

Upvotes: 0

Related Questions