javascript - Angularjs ng-repeat, ng-form and validation error -
a simplified version of code:
<!doctype html> <html ng-app="main"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script> <script> var app = angular.module("main", []); app.controller("testcontroller", function($scope) { $scope.addresses = [{street: ""}, {street: ""}]; $scope.next = function() { if ($scope.addressmainform.addressform.$valid) { console.log("valid"); } else { console.log("invalid"); } $scope.addresses.push({street: ""}); }; $scope.remove = function(index) { $scope.addresses.splice(index, 1); }; }); </script> </head> <body> <div ng-controller="testcontroller" style="width: 500px;"> <form name="addressmainform"> <div ng-repeat="address in addresses"> <ng-form name="addressform"> <input ng-model="address.street" required name="street" type="text" placeholder="street" /> <button ng-if="$index > 0" ng-click="remove($index)">remove</button> </ng-form> <br> </div> </form> <br> <button ng-click="next()">next</button> </div> </body> </html>
which looks in browser this:
when click "remove" , "next" - javascript error produced:
error: $scope.addressmainform.addressform undefined
why undefined if there still 1 element remaining in array? otherwise works fine (console.log
output), until elements removed last 1 , "next" clicked.
when call $scope.addressmainform.addressform.$valid
, attempting call check see if adressform
element valid, remove
function has removed addresses
entry associated element. form indeed still exists, call becomes illegal.
try this:
<!doctype html> <html ng-app="main"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script> <script> var app = angular.module("main", []); app.controller("testcontroller", function($scope) { $scope.addresses = [{street: ""}, {street: ""}]; $scope.next = function() { if ($scope.addressmainform.$valid) { console.log("valid"); } else { console.log("invalid"); } $scope.addresses.push({street: ""}); }; $scope.remove = function(index) { $scope.addresses.splice(index, 1); }; }); </script> </head> <body> <div ng-controller="testcontroller" style="width: 500px;"> <form name="addressmainform"> <div ng-repeat="address in addresses"> <ng-form name="addressform"> <input ng-model="address.street" required name="street" type="text" placeholder="street" /> <button ng-if="$index > 0" ng-click="remove($index)">remove</button> </ng-form> <br> </div> </form> <br> <button ng-click="next()">next</button> </div> </body> </html>
Comments
Post a Comment