How would I add focus to the newly created field? See example thus far: http://jsfiddle.net/aERwc/165/
$scope.addField = function() {console.log('hi');
$scope.fields[$scope.keyToAdd] = $scope.valueToAdd;
$scope.setFieldKeys();
$scope.keyToAdd = '';
$scope.valueToAdd = '';
}
You can use this approach however it will require to add animation to your ng-repeat. see ng-repeat animation complete callback
Basically in callback call element.focus()
.animation('.repeat-animate', function () {
return {
enter: function (element, done) {
element.hide().show(100, function(){
var scope = element.scope();
scope.$evalAsync(function(){
element.find(':last')[0].focus();
});
});
}
};
});
UPDATED CODEPEN: http://codepen.io/ev-tt/pen/BNXBmd?editors=101
To me, this seems like the simplest way to do it:
Code Pen
HTML
<html ng-app='app'>
<body ng-controller='MainController as vm'>
<input ng-repeat='thing in vm.things'>
<hr />
<button ng-click='vm.addThing()'>Add Thing</button>
</body>
</html>
JS
angular
.module('app', [])
.controller('MainController', MainController)
;
function MainController($timeout) {
var vm = this;
vm.things = [{}];
vm.addThing = function() {
vm.things.push({});
$timeout(function() {
// have to do this in a $timemout because
// we want it to happen after the view is updated
// with the newly added input
angular
.element(document.querySelectorAll('input'))
.eq(-1)[0]
.focus()
;
}, 0);
};
}
Personally, I would actually use jQuery and make the code even simpler:
$('input:last').focus();
Instead of:
angular
.element(document.querySelectorAll('input'))
.eq(-1)[0]
.focus()
;
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