2017-07-25 74 views
1
<html> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
    <script> 
     var app = angular.module('myApp', []); 
     app.controller('validateCtrl', function ($scope, $compile) { 
      $scope.createField = function() { 
       var lname = '<label>LastName : </label><input type="text" name="last" ng-model = "last" required/> Valid: {{myForm.last.$valid}}<br>'; 
       var tdiv = document.createElement("div"); 
       tdiv.innerHTML = lname; 
       $compile(tdiv)($scope); 
       document.getElementById("container").appendChild(tdiv); 
      } 
     }); 
    </script> 
    <body> 
     <h2>Validation Example</h2> 
     <form ng-app="myApp" 
       ng-controller="validateCtrl" 
       name="myForm"> 
      <div id="container"> 
       Firstname : <input type="text" name="first" ng-model="first" required/> 
       Valid: {{myForm.first.$valid}} [ Here element state is displayed whether element is valid or not correctly but if we add element dynamically with create button it is not showing either valid or not. ] 

      </div> 
      <button type="button" ng-click="createField();" value="Create">Create</button> 
     </form> 
    </body> 
</html> 

這裏元素狀態顯示元素是否有效或不正確的,但如果我們用動態的添加元素創建按鈕,它沒有顯示任何有效或無效。無法獲取表單輸入元件狀態動態添加輸入元素angularJS

回答

0

這不起作用,因爲你編譯你的動態輸入分離,因此他們無法通過FormController註冊自己。爲了使它工作,你首先需要將你的元素插入到DOM中,並在之後進行編譯。所以基本上只需將您的$compile(tdiv)($scope);一行下移。最後你應該有這個:

 $scope.createField = function() { 
      var lname = '<label>LastName : </label><input type="text" name="last" ng-model = "last" required/> Valid: {{myForm.last.$valid}}<br>'; 
      var tdiv = document.createElement("div"); 
      tdiv.innerHTML = lname; 
      document.getElementById("container").appendChild(tdiv); 
      $compile(tdiv)($scope); 
     } 
+0

謝謝,它工作正常。 – Vivek

+0

如果此答案已解決您的問題,請點擊複選標記,考慮[接受它](https://meta.stackexchange.com/q/5234/179419)。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 – xReeQz