Liron Ilayev Liron Ilayev - 2 months ago 6
Javascript Question

Button click only works once

I'm still new to this, so it might be a rookie mistake but I can't find a solution online for a day now. I have a button that I want to be clickable. Once it's clicked a new 'input' tag is supposed to be appended to the end of the div "forPassengers", and it actually works but it only works once. After one click it stops working and doesn't append any more of the tags I want to add. I'm adding the code from the div tag and the javascript code of the controller document:

Controller:

app
.controller('multipleFlightsController', function ($scope, $http, $location) {
$scope.addPassenger = function () {
document.getElementById('forPassengers')
.innerHTML += '<input class="form-control airport ng-pristine ng-untouched ng-valid" type="text" ng-model="additionalPassengers" placeholder="#" tabindex="0" aria-invalid="false"> ';
};
/*..... more code*/


HTML:

<div id="forPassengers" class="col-lg-2 form-group">
<label># of other passengers</label>
<button id="buttonForPassenger" type="button" class="btnBlue" ng-click="addPassenger()">Add passenger</button>
<input class="form-control airport" type="text" ng-model="additionalPassengers" placeholder="#">
<input class="form-control airport" type="text" ng-model="additionalPassengers" placeholder="#">
</div>


Bare in mind, I'm still very very new to javascript and html and web development in general so it may seem as a stupid mistake to you but I really can't find the problem.

Answer

Use your $scope:

$scope.passengers = [];
$scope.addPassenger = function () {
    $scope.passengers.push({});
};

and then with ng-repeat:

<!-- use ng-repeat... -->
<input ng-repeat="passenger in passengers" class="form-control airport ng-pristine ng-untouched ng-valid" type="text" ng-model="additionalPassengers" placeholder="#" tabindex="0" aria-invalid="false">