如何将值推到数组的特定位置

时间:2021-02-01 01:39:24

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'}];

孩子年龄数组美元范围。年龄= [{childCount:'1 Yr'},{childCount:'2 Yrs'}];

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

我想把跟随值推到第一个位置。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

谁能帮我解决这个问题吗?谢谢

2 个解决方案

#1


2  

You are trying to push wrong format of the data. It should be inserted as

您正在尝试输入错误的数据格式。它应该插入为

$scope.age.splice(0,0,{childCount:"Child 1 Age"})

#2


3  

Instead of using .push use .unshift

不要使用。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.

我还建议使用ng-options而不是自己做ng-repeat,但在这种情况下,这并不会带来功能上的差异。

#1


2  

You are trying to push wrong format of the data. It should be inserted as

您正在尝试输入错误的数据格式。它应该插入为

$scope.age.splice(0,0,{childCount:"Child 1 Age"})

#2


3  

Instead of using .push use .unshift

不要使用。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.

我还建议使用ng-options而不是自己做ng-repeat,但在这种情况下,这并不会带来功能上的差异。