Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 表格最佳实践(angularjs 1.6)_Javascript_Angularjs - Fatal编程技术网

Javascript 表格最佳实践(angularjs 1.6)

Javascript 表格最佳实践(angularjs 1.6),javascript,angularjs,Javascript,Angularjs,我已经看到了实现表单的不同方法及其背后与控制器交互的逻辑,我想知道遵循的最佳方法是什么 例如: <form name="myForm" ng-submit="submit(user)"> username: <input name="username" ng-model="user.username"> age: <input name="age" ng-model="user.age"> </form> 用户名: 年龄: 在该示例中

我已经看到了实现表单的不同方法及其背后与控制器交互的逻辑,我想知道遵循的最佳方法是什么

例如:

<form name="myForm" ng-submit="submit(user)">
  username: <input name="username" ng-model="user.username">
  age: <input name="age" ng-model="user.age">
</form>

用户名:
年龄:
在该示例中,控制器中的
submit()
方法将有3种方式从表单中提取
username
age

  • 使用
    $scope.myForm
    对象。此对象还包含与表单验证相关的信息
  • 使用
    $scope.user
    对象
  • 使用传递给
    submit()
    方法的
    user
    变量

所以我的问题是,什么是最佳实践?

使用传递给submit(用户)的用户变量是最好的方法。

让我们看看这三种方法:

  • $scope.myForm
    应仅用于表单验证目的。我通常通过选中
    $scope.myForm.$invalid
    来禁用提交按钮

  • $scope.user
    -它会限制
    submit
    函数仅使用此变量,并降低其可重用性。您还需要输入more-
    $scope
    部分,这是我的学究作风

  • 我更喜欢第三种方法,因为它增加了
    submit
    函数的可重用性


  • 不要使用$scope,而是将所有内容绑定到控制器。它应该是这样的:

    <form name="$ctrl.myForm" ng-submit="$ctrl.submit()">
      username: <input name="username" ng-model="$ctrl.user.username">
      age: <input name="age" ng-model="$ctrl.user.age">
    </form>
    
    
    用户名:
    年龄:
    
    传递$ctrl.user来为我提交没有任何意义,但这更多的是风格问题

    另外,对于简单的情况,你们不需要控制器中的表单对象,但当事情变得复杂时,你们会发现没有表单的生活非常困难。作为一个实例,尝试在某些字段上添加异步验证,这应该在blur和form submit上都发生(如果blur上的验证尚未完成)