[英]AngularJS $scope form attribute is undefined after ng-submit
我從Angular開始,我仍然對語法和我可以編碼以獲得相同結果的許多不同方式感到困惑。
我的最新問題是,提交表單時,無法通過執行$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(包含在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();
}
}]);
它總是警告“未定義”,我可以通過以下操作獲取值
$event.target.username
就像在流星上一樣。
有任何想法嗎?
@ EDIT1
我添加了用戶作為模型的對象
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)
}
}]);
我仍然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>
在控制器內定義$ scope,如下所示。 因為屬性是在控制器初始化時注冊到控制器的$ 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)
}
}]);
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.