尝试:
JS:
$scope.addPhone = function() {
$scope.phones.push('Phone' + Math.random());
$scope.focusIndex = $scope.phones.length-1;
}
DEMO
解决方案使用自定义属性:
<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
很好的解决方案。最佳做法是在未来的角色版本发生冲突的情况下,不要用ng前缀自定义指令。 –
@粗糙的兔子:这真是一个很好的观点。谢谢 –
我刚刚用Chrome v52测试了这个解决方案(DEMO plunker link):我没有把注意力放在最后一个INPUT上......这个解决方案能否被淘汰? – Didier68