0

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); } }); 
2
  • 3
    $scope.viaPoints.push("val:''"); doesnt look right. Maybe you mean like this $scope.viaPoints.push({"val:''"}); ?CommentedAug 27, 2016 at 10:56
  • Np.Glad to helps.CommentedAug 27, 2016 at 12:21

1 Answer 1

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())

1
  • @BenjaminLawson did I solve your problem? If I did, please mark this as the correct answer, if you see fit
    – flapas
    CommentedAug 30, 2016 at 12:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.