在angularjs中自动对焦输入字段

时间:2014-01-24 18:30:08

标签: angularjs angularjs-directive angularjs-scope

我已经创建了一个自动对焦于文本框的指令

 (function () {
'use strict';
 angular.module('commonModule').directive('srFocuson',function(){ 
    return {
        restrict: 'A',
        require: 'ngModel',
       link: function (scope, element, attrs) {
            scope.$watch(attrs.focusMe, function (value) {
                if (value === true) {
                    console.log('value=', value);
                   element[0].focus();
                    scope[attrs.focusMe] = false;

                }
            });
        }
    };
});

})();

现在我想将该指令绑定到我的文本框。我试图绑定到输入字段但它不起作用。

 <input placeholder="SR ID, SSN/ITIN, or School ID" sr-focuson="focusMe" type="text"        
  id="form_ID" name="searchId" autofocus
            data-ng-model="vm.searchCriteria.searchId"
            maxlength="20" class="form-control">

http://plnkr.co/edit/A39duXhGvCedAaVuB3uQ?p=preview

2 个答案:

答案 0 :(得分:1)

我把你的想法弄得一团糟。 http://jsfiddle.net/fLaAG/

有点不清楚你要更新scope.focusMe的位置,所以我创建了一个显式按钮,将该值设置为true。

<button type="button" ng-click="Focus()" type="button">Focus</button>
...
$scope.Focus = function() {
    $scope.focusMe = true;
};

另外我正在设置一个隔离范围,所以我只能看一下我给它的字符串。

scope: {
    focusMe: '=focusOn'
},

希望这有帮助

答案 1 :(得分:0)

这是一种使用内置角度功能的方法,从角度文档的阴暗深处挖掘出来。请注意“链接”属性如何分为“前”和“后”,用于预链接和后链接功能。

Working Example: http://plnkr.co/edit/Fj59GB

// this is the directive you add to any element you want to highlight after creation
Guest.directive('autoFocus', function() {
    return {
        link: {
            pre: function preLink(scope, element, attr) {
                console.debug('prelink called');
                // this fails since the element hasn't rendered
                //element[0].focus();
            },
            post: function postLink(scope, element, attr) {
                console.debug('postlink called');
                // this succeeds since the element has been rendered
                element[0].focus();
            }
        }
    };
});
<input value="hello" />
<!-- this input automatically gets focus on creation -->
<input value="world" auto-focus />

Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile