I have a list of model objects that are presented in the view with an ng-repeat
directive on input
elements, being editable. There is an Add new
button to add a new item to the list, which creates a new empty input
. But as soon as the new empty input is created in the view, I want it to be focused and ready to be edited. I'm not sure how to go about this, since I have little access to the DOM in the controller and the controller is where I am adding the new empty model to the list.
I'm still new with AngularJS, writing this app to learn. So, do let me know any other things I've done wrongly in the implementation.
Plunker: http://plnkr.co/Ig4OtuUtFatIknO1Kfxi
Interesting pieces of code:
HTML:
<body ng-controller=PlanetCtrl>
<div>
<input ng-repeat='it in planets' type=text ng-model=it.name edit-spotlight>
</div>
<button ng-click=addNew() class='btn btn-primary'>+ Add new item</button>
<div id=spotlight-shadow></div>
</body>
Javascript:
angular.module('planet-man', []).
// ... editSpotlight directive ...
function PlanetCtrl ($scope) {
$scope.planets = [
{name: 'Mercury'},
{name: 'Venus'},
{name: 'Earth'},
{name: 'Mars'}
];
$scope.addNew = function () {
$scope.planets.push({name: ''});
};
}
As you can see from the plunker, when the Add
button is clicked, a new input is added to the view, but one has to manually focus it. I want it to receive focus (and have the spotlight effect appear) immediately on clicking the Add
button.
Thank you.