Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set autofocus in partial views using angularjs?

In my project am using partial pages more. i couldn't set auto focus on text box control whereas it is working in normal pages.

This is my partial page view :

<body ng-app="app" ng-controller="myCtrl">

        <section>
             <input type="text" focus-me/>
             <input type="text" />
                 <a ng-click="show()">click</a>
            <section>
        <section ng-show="show">
            <input type="text" focus-me/>
            </section>
    </body>

This is my js :

var app = angular.module("app", []);
app.controller('myCtrl', function($scope) {
}); 
 $scope.show = false;

$scope.show = function() {
    $scope.show = true;
};
angular.module('ng').directive('focusMe', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
                    $timeout( function () { element[0].focus(); } );
                }


    };
});

1)The focus-me works in first section of html but not in second section because its being shown through ng-show as a partial view. 2)And the focus goes to the last item while i use ng-repeat but it needs to set in first item.

can anyone please help me with these two questions?

like image 926
Ninja Avatar asked Feb 12 '23 01:02

Ninja


1 Answers

Your first issue is because although ng-show is controlling whether you can see the dom element in the view, it is actually in the dom, so your directive will run when it is placed into the dom. If instead you use ng-if then it will work as you expect.

The second issue is actually working as designed. Your directive invokes an immediate timeout to focus on the element and they are all working in the ng-repeat. The reason why it focuses on the last one is because that is the last one to emit the timeout focus event.

If you want only the first one in the list to be focused then can use the $first variable to have directive only work on the first element in the list.

Here is a working sample: http://plnkr.co/edit/1GbvaB?p=preview

like image 62
JoseM Avatar answered Feb 21 '23 09:02

JoseM