表单在控制器中未定义

时间:2014-10-22 15:58:37

标签: javascript angularjs forms input

我有一张表格......

<form name="userForm" ng-submit="setUsers()">
  <input type="number" class="form-control" name="users" ng-model="users.num" required>
  <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Continue</button>
</form>

在我的控制器中,我想查看表单是否为$pristine ...

angular.module('myApp')

.controller('myController', ['$http', '$scope', function($http, $scope) {
  $scope.userForm = {};
  $scope.users = {};

  console.log($scope.userForm) //empty object
  console.log($scope.userForm.$pristine); // undefined
  console.log($scope.users); //empty object
  console.log($scope.users.num); //undefined

}]);

我做错了什么我无法在控制器中获取该表单?我正在使用AngularJs 1.3

谢谢!

2 个答案:

答案 0 :(得分:0)

您无法访问表单,因为您尝试在表单存在之前执行此操作。请参阅下面的代码示例,它可以帮助您。

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

app.controller('fCtrl', function($scope){
  
 $scope.setForm = function (form) {
    $scope.userForm = form;     
    $scope.users = {};
 
   console.log($scope.userForm) //empty object
   console.log($scope.userForm.$pristine); // undefined
   console.log($scope.users); //empty object
   console.log($scope.users.num); //undefined
   
}
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="fCtrl">

    <form name="userForm" ng-submit="setUsers()">
      <input type="number" class="form-control" name="users" ng-model="users.num" required>
      <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Continue</button>

      <span ng-init="setForm(userForm);"></span>
    </form>
  </div>
</div>

答案 1 :(得分:0)

您必须等待表单可用。如果在加载控制器后访问它,您将能够访问它。

使用以下内容快速测试:

 console.log($scope.userForm); // undefined

 $scope.logForm= function(){
    console.log($scope.userForm); // defined
 };

打开您的控制台并查看此框http://jsbin.com/loqic/1/edit?js,output