AngularJS $scope form attribute is undefined after ng-submit

随声附和 提交于 2020-01-05 03:09:47

问题


I'm starting with Angular and I'm still very confused with syntax and the many different ways I can code to get the same result.

My latest problem is that when I submit a form, I can't get its values by doing $scope.attribute_name

HTML

<body ng-app="myApp">
        <div ng-include src="'menu.html'"></div>
        <div id="container" ng-controller="MainController">
            <div ui-view></div>
        </div>
    </div>

login.html (included by Route)

<form name="form" name='' action="" ng-submit='login($event)'>
    <input type="text" name='username' ng-model='username' required />
    <input type="text" name='password' ng-model='password' required />
    <button>Enviar</button>
</form>

JS

 var app = angular.module('myApp', ['ui.router']);
 app.controller('MainController',['$scope',function($scope){
        $scope.login = function ($event){
            alert($scope.username)
            $event.preventDefault();
        }
}]);

It always alert "undefined" I can get the values by doing the following

$event.target.username

Just like on Meteor.

Any ideas?

@edit1

I added user as the model's object

HTML

<form name="form" name='teste' action="" ng-submit='login($event)'>
    <input type="text" name='username' ng-model='user.username' required />
    <input type="text" name='password' ng-model='user.password' required />
    <button>Enviar</button>
</form>

JS

app.controller('MainController',['$scope',function($scope){
    $scope.login = function ($event){
        alert($scope.user.username)
}
}]);

I still get undefined though


回答1:


<form name="form" name='teste' action="" ng-submit='login()'>
    <input type="text" name='username' ng-model='user.username' required />
    <input type="text" name='password' ng-model='user.password' required />
    <button>Enviar</button>
</form>

define your $scope inside the controller as below. Because attributes are registered to the $scope of the controller when the controller initializes.

app.controller('MainController',['$scope',function($scope){
    $scope.user={}; //DEFINE $scope variable if dot is given to variable.
    $scope.login = function (){
        alert($scope.user.username)
}
}]);

Thanks



来源:https://stackoverflow.com/questions/32262075/angularjs-scope-form-attribute-is-undefined-after-ng-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!