autofocus doesn't work when used with ng-include

左心房为你撑大大i 提交于 2019-12-13 15:43:07

问题


I want to set focus to one of the input box in partial view like .

and including this by

This is working fine when page loads for the first time. but when I change the partials autofocus doesn't work .

I believe it is because of autofocus work on pageload how can it make work here


回答1:


I am not sure how to fix the problem of page reload but I think we can work out another solution here. I wrote a small directive once to conditionally set focus on an input element.

Here is the code:

function SetFocusDirective($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.setFocus);
            scope.$watch(model, function (value) {
                if (value === true) {
                    element[0].focus();
                }
            });
            element.bind('blur', function () {
                scope.$apply(model.assign(scope, false));
            });
        }
    };
}

SetFocusDirective.$inject = ['$parse'];

app.directive('setFocus', SetFocusDirective);

And here is how you can use it:

<input type="text" ng-model="firstName" set-focus="autofocusFirstName">

Where autofocusFirstName is a $scope variable which should have a boolean value.

So every time your partials load, all the directives inside them will get linked and do their jobs. If you end up using this directive, you should be able to achieve what you want.



来源:https://stackoverflow.com/questions/24577839/autofocus-doesnt-work-when-used-with-ng-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!