简体   繁体   中英

Adding a variable to a group of array

I'm using angular js to produce to add an array and display it as we go along. So far the given code adds an array to the list but it doesn't keep adding the array with the press of the function.

I'm quite new to angular and i think there's something I'm missing but right now I'm stuck.

The html code has a button linked which is supposed to carry out the function.

 var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.records = ["Testing Task 5.1", "Downloaded Task 5.1"]; $scope.addArray = function() { $scope.records.unshift("saddfadffas") } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-controller="myCtrl" class="container"> <p> <h3>Status: </h3> <input type="text" ng-model="additem"> <button ng-click="addArray()">function</button> </p> <ul ng-repeat="x in records"> <li>{{x}}</li> </ul> </div> 

Try push rather than unshift ? Sorry I am not at my computer right now so can't verify this, but I'm pretty sure this will solve the problem

You can resolve this issue by having the items in your array be keyed by their position rather than their value. To do this, you can use track by $index . Hope this helps!

 var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.records = ["Testing Task 5.1", "Downloaded Task 5.1"]; $scope.addArray = function() { $scope.records.unshift("saddfadffas") } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="myCtrl" class="container"> <p> <h3>Status: </h3> <input type="text" ng-model="additem"> <button ng-click="addArray()">function</button> </p> <ul ng-repeat="x in records track by $index"> <li>{{x}}</li> </ul> </div> 

EDIT: Perhaps your intention is

$scope.records.unshift($scope.additem)

rather than

$scope.records.unshift("saddfadffas")

but I am assuming you are perhaps running into an error we can't see from the excerpt you posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM