简体   繁体   中英

How to push a new item into an array of objects using AngularJS?

On my website are a list of user created via points. The user starts with one, and then if they wish to add another they can click “add” and it should add a new object inside of the array with an empty value and the user can input a new value. The user can continue adding until they have 5. How would I do this? Below is my code.

I want:

  1. User can create via points which add a new item with val="" and then the user can change the value with the input.
  2. After 5 via points no more are allowed.

Thank you for any help!

//HTML

<table>
    <tr ng-repeat="item in viaPoints">
        <td>

            <p class="title-icon form-label">VIA LOCATON {{$index + 1}}</p>

            <button style="bottom: -3px;" class="transparent position pull-right" ng-click="removeViaPoint($index)">
                <img src="images/icons/close-14.png">
            </button>

            <input class="form" id="drop-off" type="text" value="{{x}}" ng-model="item.val">

        </td>
    </tr>
</table>

<button class="add" ng-click="addViaPoint()">+ ADD MORE LOCATIONS</button>
<button class="okay okay-full">OKAY</button>



//Angular


var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

//Via Point Objects


$scope.viaPoints = [

{val:"Hanoi"}

]

//Push Via Points

$scope.addViaPoint = function () {
    $scope.viaPoints.push("val:''");
}

//Remove Via Point

$scope.removeViaPoint = function (x) {
    $scope.viaPoints.splice(x, 1);
}

});

By making

$scope.addViaPoint = function () {
  $scope.viaPoints.push("val:''");
}

only makes you add a string to the array. If you want to add an object, just write instead

$scope.addViaPoint = function () {
  $scope.viaPoints.push({val:''});
}

You're now adding a new object with a property val set to ''

As for not allowing more than 5 points, you could just make a logic gate on your function, like:

if ($scope.viaPoints.length === 5) return;

Or you can opt for a more user-friendly way of deactivating the button depending on that length, like:

<button class="add"
        ng-click="addViaPoint()"
        ng-disabled="$scope.viaPoints.length === 5">
  + ADD MORE LOCATIONS
</button>

(although you should use a more flexible approach with a function like reachedMaxViaPoints() )

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