简体   繁体   English

ng-submit后未定义AngularJS $ scope表单属性

[英]AngularJS $scope form attribute is undefined after ng-submit

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. 我从Angular开始,我仍然对语法和我可以编码以获得相同结果的许多不同方式感到困惑。

My latest problem is that when I submit a form, I can't get its values by doing $scope.attribute_name 我的最新问题是,提交表单时,无法通过执行$scope.attribute_name来获取其值

HTML 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) login.html(包含在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 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 @ EDIT1

I added user as the model's object 我添加了用户作为模型的对象

HTML 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 JS

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

I still get undefined though 我仍然undefined

<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. 在控制器内定义$ scope,如下所示。 Because attributes are registered to the $scope of the controller when the controller initializes. 因为属性是在控制器初始化时注册到控制器的$ scope的。

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 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM