angularjs how to push a value to specific position of array

Lara picture Lara · Jan 20, 2014 · Viewed 7.9k times · Source

I have a select dropdown which gets value from an array. I want to push a value to the first position of the array if the condition is true.

<select name="child_age">
    <option ng-repeat="child_age in age">{{child_age.childCount}}</option>
</select>

Child age Array $scope.age = [{childCount:'1 Yr'},{childCount:'2 Yrs'}];

I want to push following Value to the first position. $scope.age.push({ childCount: 'Child 1 Age' })

But it has been added to the last position.

Also I tried following code as well

$scope.age.splice(0,0,"Child 1 Age")

It shows the position. But not displaying the value

Can anyone help me to solve this issue? Thanks

Answer

Explosion Pills picture Explosion Pills · Jan 20, 2014

Instead of using .push use .unshift

I would also suggest using ng-options instead of doing the ng-repeat yourself, but that shouldn't make a functional difference in this case.