按钮单击仅适用一次

时间:2016-09-11 16:56:44

标签: javascript jquery html

我有一个按钮,一旦点击它就会在“forPassengers”div的末尾添加一个新的输入元素,但它只能工作一次。点击一下就不再可以点击了。

控制器:

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>

工作解决方案(编辑)

最终解决我问题的是实际使用AngularJS而不是通过document.getElementById函数访问input元素。

2 个答案:

答案 0 :(得分:2)

使用$ scope:

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

然后使用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">

答案 1 :(得分:1)

为什么它有效的原因是angularJS在引擎盖下做了相当多的魔术。通过覆盖对象的innerHTML,您可以从子节点擦除角度的绑定。

按照建议使用ng-repeat。

 $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有一套很好的工具来控制你的视图合成和模板: NG-重复 NG-秀 NG-隐藏 NG-如果

尽量避免自己修复DOM。