参数未传递给ng-submit

时间:2018-06-04 13:55:39

标签: javascript angularjs

我有一个函数重置(用户名),输出输入ng-model="username"输入字段的内容。为什么它不会出现在控制台中?

这是我的功能

$scope.reset = function (username) {
   console.log(username);
};

以及我提交表单的方式

<form name="Form" ng-controller="ResetController" ng-submit="reset(username)">
<div>
   <div class="row top5">        
      <label for="username">Username</label>
      <div class="col-xs-4">
         <input type="text" id="username"  placeholder="" maxlength="255"
          ng-model="username" required autofocus>
      </div>  

   <div>
      <div class="col-xs-5">          
         <button translate class="btn btn-secondary" type="submit">Reset</button>
      </div>
   </div>
</div>   
</form>

按要求提供控制器

app.controller("ResetController", function ($scope) {
   $scope.username='';
   $scope.reset = function (username) {
      console.log('username = ', username);
   };
});

1 个答案:

答案 0 :(得分:2)

我相信你确实拥有ng-app以及除此表单之外的所有其他内容,但是如果你将输入作为对象的属性而不是直接作为$ scope操作,那么DOM会更好地处理它。属性。查看此here的答案。并在代码中注明我如何将用户名附加到$scope.object.username

&#13;
&#13;
var app = angular.module('myApp',[])

app.controller('ResetController',['$scope',function($scope){

   $scope.object = {};
   $scope.reset = function(username){
    console.log(username);
   };
   
}])
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <form name="Form" ng-controller="ResetController" ng-submit="reset(object.username)">
  <div>
     <div class="row top5">        
        <label for="username">Username</label>
        <div class="col-xs-4">
           <input type="text" id="username"  placeholder="" maxlength="255"
            ng-model="object.username" required autofocus>
        </div>  

     <div>
        <div class="col-xs-5">          
           <button translate class="btn btn-secondary" type="submit">Reset</button>
        </div>
     </div>
  </div>  
  </form>
</div>
&#13;
&#13;
&#13;