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

2024-01-26

我从 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(由路由包含)

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


<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)
}
}]);

Thanks

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJS $scope 表单属性在 ng-submit 后未定义 的相关文章

随机推荐