[英]AngularJS push item to first or 0 index of $scope array
Please help me implement this function. 请帮我实现这个功能。 I have an array of items in my $scope
. 我的$scope
有一系列项目。 Now, when I click on the Add Item button, I want to push a new item to the first index or 0 index of that array. 现在,当我单击Add Item按钮时,我想将一个新项目推送到该数组的第一个索引或0索引。 Thanks in advance. 提前致谢。 :) :)
Here's a working jsFiddle to start with: http://jsfiddle.net/limeric29/7FH2e/ 这是一个有用的jsFiddle : http : //jsfiddle.net/limeric29/7FH2e/
HTML: HTML:
<div ng-controller="Ctrl">
{{data}}<br/>
<input type="button" ng-click="addItem()" value="Add Item" />
</div>
JavaScript: JavaScript的:
function Ctrl($scope) {
$scope.data = [
new String('Item 5'), new String('Item 4'), new String('Item 3'), new String('Item 2'), new String('Item 1')];
$scope.addItem = function () {
var c = $scope.data.length + 1;
var item = new String('Item ' + c)
$scope.data.push(item);
};
}
You can use the unshift function. 您可以使用unshift功能。
function Ctrl($scope) {
$scope.data = [
new String('Item 5'), new String('Item 4'), new String('Item 3'), new String('Item 2'), new String('Item 1')];
$scope.addItem = function () {
var item = new String('Item ' + c)
$scope.data.unshift(item);
};
}
Solved my problem by using splice() instead of push() and assigning to what array index to insert. 通过使用splice()而不是push()并分配要插入的数组索引解决了我的问题。
HTML: HTML:
<div ng-controller="Ctrl">
<pre>{{data}}</pre><br/>
<input type="button" ng-click="addItem()" value="Add Item" />
</div>
Javascript: 使用Javascript:
function Ctrl($scope) {
$scope.data = [
new String('Item 4'), new String('Item 3'), new String('Item 2'), new String('Item 1')];
$scope.addItem = function () {
var c = $scope.data.length + 1;
var item = new String('Item ' + c)
$scope.data.splice(0, 0, item);
};
}
Here's the updated fiddle for this. 这是更新的小提琴 。 http://jsfiddle.net/limeric29/xvHNe/ http://jsfiddle.net/limeric29/xvHNe/
$scope.data.unshift(item);
一线,不知道为什么其他人这么难
Try this: 试试这个:
function Ctrl($scope) {
$scope.data = [
new String('Item 4'), new String('Item 3'), new String('Item 2'), new String('Item 1')];
$scope.addItem = function () {
var c = $scope.data.length + 1;
var item = new String('Item ' + c);
$scope.data.push(item);
};
}
I think, not necessary this operation. 我想,没必要这个操作。 You can solve it like this; 你可以像这样解决它;
<div ng-controller="Ctrl">
<!-- "$index" is short parameter, "true" statment is reverse parameter -->
{{data | reverse:$index:true}}<br/>
<input type="button" ng-click="addItem()" value="Add Item" />
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.