如何从表单输入中获取数据

时间:2016-10-22 18:10:00

标签: angularjs ionic-framework

我是移动开发的新手,尤其是使用Ionic。请帮帮我

我有我的路线代码

.state('auth', {
url: '/auth',
templateUrl: 'templates/login.html',
controller: 'AuthCtrl'

我的login.html

代码
<ion-view view-title="Login" name="login-view">
<ion-content class="padding">
    <div class="list list-inset">
        <label class="item item-input">
            <input type="text" placeholder="Mobile Number" ng-model="mobile_number">
        </label>
        <label class="item item-input">
            <input type="password" placeholder="Password" ng-model="password">
        </label>
    </div>
    <button class="button button-block button-calm" ng-click="login()">Login</button>
</ion-content>

和我的AuthCtrl

.controller('AuthCtrl', function($scope,$auth,$state) {

$scope.login = function() {
    var credentials = {
        mobile_number : $scope.mobile_number,
        password : $scope.password,
    }
    console.log(credentials);
    $auth.login(credentials).then(function(data) {
        // If login is successful, redirect to the users state
        $state.go('tab.dash', {});
    });
}

})

调用 console.log(凭据)时,我总是得到对象{mobile_number:undefined,密码:undefined} 我总是把值放在我的表单中,但它总是未定义的。为什么呢?

3 个答案:

答案 0 :(得分:7)

首先初始化您的范围凭据模型:

$scope.credentials = {
   'mobile_number' : ''
   'password' : '',
 }

然后将输入绑定到范围属性:

<input type="text" placeholder="Mobile Number" ng-model="credentials.mobile_number">


<input type="password" placeholder="Password" ng-model="credentials.password">

并使用现在包含表单数据的$scope.credentials

$auth.login($scope.credentials).then(function(data) {
    // If login is successful, redirect to the users state
    $state.go('tab.dash', {});
});

答案 1 :(得分:2)

您的凭据对象未绑定到范围。看起来你需要在登录之外声明$ scope.credentials。同样在输入上,ngModel应该绑定到credentials.password和credentials.mobile_number。

答案 2 :(得分:1)

实际上它对我有用,我做了一点plunker来测试它。我遇到了类似的问题,因为我在输入中添加了ng-pattern和ng-minLength指令。在这种情况下,除非输入值是有效的模式和长度,否则将获得未定义。为了解决这个问题,我在你的输入元素中添加了属性

<input type="tel" ng-model="credentials.mobile_number" 
  ng-model-options="{allowInvalid:true}"/>

我希望有所帮助,祝你好运

相关问题