Please help me implement this function. I have an array of items in my $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. Thanks in advance. :)
Here's a working jsFiddle to start with: http://jsfiddle.net/limeric29/7FH2e/
HTML:
<div ng-controller="Ctrl">
{{data}}<br/>
<input type="button" ng-click="addItem()" value="Add Item" />
</div>
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.
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.
HTML:
<div ng-controller="Ctrl">
<pre>{{data}}</pre><br/>
<input type="button" ng-click="addItem()" value="Add Item" />
</div>
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/
$scope.data.unshift(item);
One line, not sure why the others made it so difficult
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