AngularJS使用ngMessages从控制器设置表单值

时间:2017-01-30 15:14:35

标签: angularjs forms ng-messages

我尝试使用角度为1.5.9的表单,但无法找到使其符合以下要求的方法:

  1. 从控制器访问表单数据(以controllerAs绑定)
  2. 请勿使用$scope绑定表单
  3. 能够从控制器设置默认值
  4. 能够更改控制器中的值
  5. 能够从控制器访问数据
  6. 使用ngMessages进行验证
  7. 我已经发表评论jsbin来说明问题和我尝试过的内容,你可以在这里找到它:http://jsbin.com/guzejelula/edit?html,js,output

    这里的每个要求都在jsbin中得到满足,除了第4个,如下所示:

    this.setLastName = function(name) { 
        // When doing this while the field is empty, the "required"
        // error disappear but the input stays empty.
        this.userForm.lastName.$setViewValue(name);
        this.userForm.lastName.$validate();  
    }
    

    我错过了什么?

2 个答案:

答案 0 :(得分:1)

据我所知,我认为你绑定了不正确的模型。

$ctrl.userForm是您的表单控制器实例。 ngModel上的“name”属性将表单控件(输入)实例公开给表单控制器实例。因此,$ctrl.userForm.lastName不会是原始模型值,它将是具有ngModelController函数的对象。

为了正确预填充表单控制器,请确保ng-model表达式具有正确的初始值。目前,您的ng-model已绑定到$scope.lastName。这就是为什么它呈现为空而不是“toto”。要解决此问题,您可以将$scope.lastName = "toto"添加到控制器,但由于您要避免使用$scope,因此只需定义this.lastName = 'toto'并使用ng-model="$ctrl.lastName"

从按钮,您只需要this.lastName = name。无需亲自致电$render$validate,因为Angular会代表您执行此操作,因为它会检测到模型值的更改。

如果它有帮助,我只是在ngModelController内写了article,如果你感兴趣的话。

希望它有所帮助!

var app = angular.module('jsbin', ['ngMessages']);

app.controller('DemoCtrl', function() {
  
  /**
   * Here I would like to set a defaut state form the form.
   * 
   * This object will be replaced by the FormController instance
   * as defined in the view by "<form name="$ctrl.userForm">" 
   * with no regards for its current content.
   */

  this.lastName = 'toto';
  this.formResults = {};
  
  /**
   * I would like to set the value of one or multiple fields
   * in the controller.
   * Here I try to set "lastName" with no success.
   *
   * I excepted something like:
   * this.userForm.setValues({
   *   lastName : 'Doe', 
   *   firstName: 'John'
   * });
   * 
   * or 
   *
   * this.userForm.setValue('lastName', 'value here');
   *
   * ...
   */
  this.setLastName = function(name) { 
    // When doing this while the field is empty, the "required"
    // error disappear but the input stays empty.
    this.lastName = name;
  }
  
  
  /**
   * Here a clean way to extract current values of the form would be handy..
   * Something like : 
   * this.userForm.getValues(); 
   */
  this.submit = function(form){
    this.formResults = {};
    if (form.$valid) {
      var values = {};
      angular.forEach(form, function (value, key) {
        if (typeof(value) === 'object' && value.hasOwnProperty('$modelValue')) {
            values[key] = value.$modelValue;
        } 
      });
      this.formResults = values;
    }
  };
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Angular JS</title>
</head>
<body ng-app="jsbin">
  <div ng-controller="DemoCtrl as $ctrl">
    
    <form name="$ctrl.userForm" novalidate>
      <label>Last Name:</label>
      <input name="lastName" ng-model="$ctrl.lastName" required="" minlength="2" type="text">
      <ng-messages for="$ctrl.userForm.lastName.$error">
          <ng-message when="minlength">Too small!</ng-message>
          <ng-message when="required">Required!</ng-message>
      </ng-messages>
      <button ng-click="$ctrl.submit($ctrl.userForm)">Submit</button>
    </form>
    
    <p>
      <button ng-click="$ctrl.setLastName('Test')">Set value to "lastName"</button>
    </p>
    
    <h2>Results</h2>
    {{$ctrl.formResults|json}}

  </div>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.9/angular-messages.js"></script>
</body>
</html>

答案 1 :(得分:0)

您需要告诉刚刚更改的视图(输入),以便渲染自身,以便更改模型值(因此新值显示在表单字段中)。

angular.element('your element id').controller('ngModel').$render()