【问题标题】:dynamically added elements are not removing from the form in angular JS动态添加的元素不会从 Angular JS 的表单中删除
【发布时间】:2016-01-18 14:22:24
【问题描述】:

我正在尝试删除动态添加到表单中的输入元素。

我正在使用下面的代码。

 var MyEle =  angular.element(document.getElementById('testID'));
  MyEle.remove();

输入元素如下动态添加

<ng-form name="TestForm" novalidate">
 <div class="testData">
    <input type="text" name="FirstName1" ng-model="FirstName1" ng-required="true"/>
    <input type="text" id="testID" name="FirstName2" ng-model="FirstName2" ng-required="true"/>
  </div>
</ng-form>                                                                           

上面的代码正在删除元素,但即使将数据输入到 First Input(FirstName1) 元素中,表单仍然显示无效。

似乎删除过程尚未完成。它不会从表单中删除。但我无法在页面上看到它。

【问题讨论】:

  • 我不知道你想在这里做什么,但 Angular 的设计并不是这样工作的......你应该在控制器中保持元素的状态并处理它在查看ng-if of ng-hide

标签: jquery html angularjs angularjs-scope


【解决方案1】:

使用 ng-if,避免在 Controller 中操作 DOM。

【讨论】:

    【解决方案2】:

    为了消除验证错误,您应该删除元素并再次编译表单,您的代码应该是这样的,您还应该将$compile 注入您的控制器

     var MyEle =  angular.element(document.getElementById('testID'));
     MyEle.remove();
     var parentElement = document.getElementsByClassName("testData");
     $compile($(parentElement)($scope);
    

    【讨论】:

      【解决方案3】:

      我可以建议您使用更 Angular 的方法来制作动态表单,请查看 sn-p

      // the main (app) module
      var myApp = angular.module("myApp", []);
      
      // add a controller
      myApp.controller("myCtrl", function($scope) {
        $scope.form = [{
          name: "FirstName1",
          required: true,
          type: "text",
          value: "billy"
        }, {
          name: "FirstName2",
          required: true,
          type: "text",
          value: "bolly"
        }];
      
        $scope.remove = function() {
          $scope.form.pop();
        };
      
        $scope.add = function() {
          $scope.form.push({
            name: "new_input_"+$scope.form.length,
            required: true,
            type: "text",
            value: "bolly_"+$scope.form.length
          });
        }
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      
      <body ng-app="myApp" ng-controller="myCtrl">
        <input type="{{input.type}}" ng-repeat="input in form" name="{{input.name}}" ng-model="input.value" ng-required="input.required" />
        <button ng-click="add()">add</button>
        <button ng-click="remove()">remove</button>
      </body>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-06
        • 2019-10-20
        • 2013-11-23
        • 2021-09-26
        • 2019-12-29
        • 2016-01-28
        • 1970-01-01
        相关资源
        最近更新 更多