问题
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