I uses ng-repeat to get multiple phone numbers
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" autofocus="autofocus">
</div>
<a ng-click="addPhone()">Add Phone</a>
In controllers
$scope.addPhone = function() {
$scope.phones.add('');
}
Whenever i add new phone, it automatically autofocus the input. It works great. But when i reload(open from link) the view, it scrolls to last entry. How do i avoid autofocus at first time the view loads. Only i want to autofocus when i add new phone.
AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
AngularJS ng-focus DirectiveThe ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.
You can use this directive: https://github.com/aikus/ng-focus-if/blob/master/ng-focus-if.js For example:
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" ng-focus-if="1==1">
</div>
<a ng-click="addPhone()">Add Phone</a>
Try:
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" ng-if="$index == focusIndex" autofocus>
<input ng-model="phone" type="text" ng-if="$index != focusIndex">
</div>
<a ng-click="addPhone()">Add Phone</a>
JS:
$scope.addPhone = function() {
$scope.phones.push('Phone' + Math.random());
$scope.focusIndex = $scope.phones.length-1;
}
DEMO
Solution using custom attribute:
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" custom-autofocus="$index == focusIndex" >
</div>
<a ng-click="addPhone()">Add Phone</a>
JS:
.directive('customAutofocus', function() {
return{
restrict: 'A',
link: function(scope, element, attrs){
scope.$watch(function(){
return scope.$eval(attrs.customAutofocus);
},function (newValue){
if (newValue === true){
element[0].focus();//use focus function instead of autofocus attribute to avoid cross browser problem. And autofocus should only be used to mark an element to be focused when page loads.
}
});
}
};
})
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With