2015-01-07 1 views
0

В следующем коде я добавляю клиента в таблицу на основе информации из формы.Зачем нужна ng-модель и имя для ng-submit?

Я обнаружил, что ng-submit не будет посылать переменные формы в addCustomer(), если входной элемент не имеет как ng-model и name, и они оба имеют такое же имя, хотя я не мог найти это документально в любом месте.

Почему это так? И поскольку это кажется избыточным, и я правильно передаю переменные?

<html ng-app="mainModule"> 
    <head> 
     <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> 
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
     <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> 
     <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> 
    </head>  
    <body ng-controller="mainController" style="padding: 20px 0"> 

     <div class="col-lg-12"> 

      <div class="panel panel-success" style="width: 500px"> 
       <div class="panel-heading">Add Customer</div> 
       <div class="panel-body"> 
        <form ng-submit="addCustomer()" role="form"> 
         <div class="form-group"> 
          <label for="firstName">First Name:</label> 
          <input type="text" class="form-control" ng-model="firstName" name="firstName"/> 
         </div> 
         <div class="form-group"> 
          <label for="lastName">Last Name:</label> 
          <input type="text" class="form-control" ng-model="lastName" name="lastName"/> 
         </div> 
         <button type="submit" class="btn btn-default">Add</button> 
        </form> 
       </div> 
      </div> 
      <div class="panel panel-info" style="width: 500px"> 
       <div class="panel-heading">Customers</div> 
       <table class="table-striped table-bordered table table-hover"> 
        <tr> 
         <th>ID</th> 
         <th>First Name</th> 
         <th>Last Name</th> 
        </tr> 
        <tr ng-repeat="customer in customers"> 
         <td>{{customer.id}}</td> 
         <td>{{customer.firstName}}</td> 
         <td>{{customer.lastName}}</td> 
        </tr> 
       </table> 
      </div> 

     </div> 
     <script> 
        var mainModule = angular.module('mainModule', []); 
          function mainController($scope) { 
           $scope.idCount = 1; 
           $scope.customers = []; 

           $scope.addCustomer = function() { 
            $scope.customers.push({id: $scope.idCount++, firstName: this.firstName, lastName: this.lastName}); 

           }; 
          } 
     </script> 
    </body> 
</html> 
+0

Просто используйте ng-model и $ scope для доступа к данным формы. –

ответ

1

Обычно вы должны создать объект клиента, а затем привязать ngModel к его свойствам.

В вашем ngController, инициализировать newCustomer:

var mainModule = angular.module('mainModule', []); 
mainModule.controller('mainController', function ($scope) { 
     $scope.idCount = 1; 
     $scope.customers = []; 
     $scope.newCustomer = { id: $scope.idCount, firstName:'', lastName:''}; 
     $scope.addCustomer = function (customer) {  
      $scope.customers.push(customer); 
      $scope.newCustomer = { id:++$scope.idCount, firstName:'', lastName:''}; 

     }; 
} 

В вашем HTML, связать ngModel с первым именем и фамилией свойств описываемого клиента - если вам не нужно делать проверку формы, имя атрибут не является необходимым.

<form ng-submit="addCustomer(newCustomer)" role="form"> 
     <div class="form-group"> 
      <label for="firstName">First Name:</label> 
      <input type="text" class="form-control" ng-model="newCustomer.firstName" /> 
     </div> 
     <div class="form-group"> 
      <label for="lastName">Last Name:</label> 
      <input type="text" class="form-control" ng-model="newCustomer.lastName"/> 
     </div> 
     <button type="submit" class="btn btn-default">Add</button> 
</form> 
+0

Отлично, спасибо, это имеет больший смысл. –