0

I'm tring to create a focus directive when i open a page with inside a form in the first input text filed.This is the directive

app.directive("getFocus", function() {
    return {
        restrict: 'AC',
        link: function(scope, element){
            console.log("focus!");
            element.focus();
        }
    }
});

and in my html input

<input id="ss" data-ng-model="item.value" type="text" data-ng-class="{'get-focus': $first}">
<input id="tt" type="text" data-ng-model="item.value" data-ng-class="{'get-focus': $first}">

i use ng-class because is a dynamic form creating cycling a json and i don't know which input is created for first. The directive seems not working. Infact, the console.log not appears in the console.. Something's wrong?

3
  • class directives will not work with ng-class. they can be used only with the html class attribute. Commented Mar 12, 2015 at 10:08
  • even if i use restrict: 'AC'? Commented Mar 12, 2015 at 10:09
  • Yes. In the above case getFocus directive will be added based on a condition. We need to re-compile the node after the class is added to get it work Commented Mar 12, 2015 at 10:12

1 Answer 1

1

I had a problem like that and I end up with this directive

angular.module('myApp').directive('autofocusIf', function($timeout) {
return {
  restrict: 'A',
  scope: {
    autofocusIf: '&'
  },
  link: function($scope, $element) {
    $scope.$watch('autofocusIf', function(shouldFocus) {
      if (shouldFocus()) {
        $timeout(function() {
          $element[0].focus();
        });
      } else {
        $timeout(function() {
          $element[0].blur();
        });
      }
    });
  }
};
})

and then in html

<div ng-repeat="repeat in repeats">
  <input type="text" autofocus-if="$first" ng-model="myModel" />
</div>
Sign up to request clarification or add additional context in comments.

7 Comments

Do you ahve your input inside ng-repeat can you make a plunker?
Ok I'm going to.. Is it a problem if I'm using uikit?
I don't think so, although I've made a working plunker for you plnkr.co/edit/ohJ62hl0rtNb1NNus9F6?p=preview
i think i found the problem..or maybe not..you have set the ng-model as input.. in my case i have another ng-model.. see my edit
is something like this: plnkr.co/edit/c0fyixdoAOmnYVilnFrO?p=preview and here not works
|

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.