Reputation: 386
I have a button which appends a new input element to the end of the "forPassengers" div once it's clicked, but it only works once. After one click it's not clickable anymore.
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>
Eventually what solved my problem was actually using AngularJS instead of accessing the input element through the document.getElementById function.
Upvotes: 1
Views: 1016
Reputation: 4489
Reason why it works once is that angularJS does quite a bit of magic under the hood. And by overriding the innerHTML of the object you wipe the angular's bindings from the child nodes.
use ng-repeat as was suggested.
$scope.people = [];
$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"> ';
$scope.people.push({name:"person" + counter});
counter= counter + 1;
};
<body ng-controller="MainCtrl">
<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="#">
<input ng-repeat="person in people" class="form-control airport ng-pristine ng-untouched ng-valid" type="text" placeholder="#" tabindex="0" aria-invalid="false" ng-model="person.name">
https://plnkr.co/edit/nkigg8j7NBDmEdeLeU4t
Angular has a very nice set of tools to control your view composition together with templates: ng-repeat ng-show ng-hide ng-if
Try to avoid fixing DOM yourself.
Upvotes: 1
Reputation: 156
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">
Upvotes: 2