我使用ng-repeat来获取多个电话号码
<div ng-repeat="phone in phones">
<input ng-model="phone" type="text" autofocus="autofocus">
</div>
<a ng-click="addPhone()">Add Phone</a>
在控制器中
$scope.addPhone = function() {
$scope.phones.add('');
}
每当我添加新手机时,它都会自动使输入聚焦。效果很好。但是,当我重新加载(从链接打开)视图时,它会滚动到最后一个条目。如何在第一次加载视图时避免自动对焦。添加新手机时,只有我要自动对焦。
尝试:
<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;
}
使用自定义属性的解决方案:
<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.
}
});
}
};
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句