Reputation: 127
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:
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);
}
});
Upvotes: 0
Views: 1184
Reputation: 583
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()
)
Upvotes: 1