AngularJS:某些未与viewmodel绑定的表单字段

时间:2018-01-10 06:04:20

标签: angularjs data-binding controller

我正在编写一个使用angularJS模型绑定输入的表单。出于某种原因,只有某些字段绑定到模型(vm.customer)。例如,绑定了vm.last_name和vm.email。但是vm.first_name和vm.gender没有从输入绑定到模型。

/* AddCustomer.js */  
(function (angular) {
  'use strict';
   angular.module('app', []);

function controller($scope) {
  var vm = this;

  vm.genders = ["Male", "Female", "Other"];
  vm.customer = {
    first_name: 'Susan',
    last_name: 'BOyle',
    email: 's.boyle@singwell.com',
    ip_address: '192.168.1.120',
    gender: vm.genders[1]
  }

  vm.addCustomer = function($scope) {
    console.log("bout to add a user");
  };
  vm.$onInit = function() {
  };
}

  // dep. injecion
  controller.$inject = ['$scope'];

  angular
  .module('app')
  .controller('AddCustomer', controller);

})(window.angular);

这是html文件

/* add-customer-view.html */
<form ng-app="app" ng-controller="AddCustomer as vm">
<pre>
  customer = {{ vm.customer | json }}
</pre>
<div class="form-row">
    <div class="form-group col-md-6">
        <label>First</label>
        <input class="form-control" type="text" ng-model"vm.customer.first_name" ng-model-options="{ updateOn: 'blur' }">
    </div>
    <div class="form-group col-md-6">
        <label>Last</label>
        <input class="form-control" type="text" ng-model="vm.customer.last_name">
    </div>
</div>
<div class="form-row">
    <div class="form-group col-md-6">
        <label class="col-form-label">Email</label>
        <input class="form-control" type="email" ng-model="vm.customer.email">
    </div>
</div>
<div class="form-row">
    <div class="form-group col-md-6">
        <div class="form-check form-check-inline" ng-repeat="gender in vm.genders">
            <input type="radio" name="gender" ng-model"vm.customer.gender" value="vm.genders[{{$index}}]">
            <label class="form-check-label">{{ gender }}</label>
        </div>
    </div>
</div>
<div class="form-row">
    <div class="form-group col-md-6">
        <label class="col-form-label">IP Address</label>
        <input class="form-control" type="text" ng-model="vm.customer.ip_address">
    </div>
</div>
<div class="form-row">
    <button type="submit" class="btn btn-primary" ng-click="vm.addCustomer()">Add Customer</button>
</div>

链接到代码段:https://codepen.io/nmnduy/pen/ypvddZ。任何见解都会非常有用!

1 个答案:

答案 0 :(得分:1)

1)您在两种情况下都错过=运算符(first_name,性别)

2)您需要按如下方式替换输入值:

<input type="radio" name="gender" ng-model="vm.customer.gender" value="{{gender}}">