我如何访问在 ng-submit 上调用的函数内的表单元素属性?
.controller('loginCtrl', function ($scope, $rootScope, $location, $window, session,$http) {
$scope.error = null;
console.log($scope);
$scope.attempt = function (url) {
//URL get passed.. but i want to fetch it from the form action attribute
var data = {username:$scope.info.u,password:$scope.info.u};
$http.post(ul, data).success(function(response) {
$scope.error = "welcome";
$rootScope.currentUser = data;
session.set('siUser', data);
$location.path('/dash');
}).error(function(reason) {
$scope.error = "failed try again" + $scope.info.p + ' ' + $scope.info.u;
});
};
})
HTML
<form role="form" ng-submit="attempt('<?=base_url('auth/login');?>')" method="post">
<fieldset>
<div class="form-group">
<input type="text" ng-model="info.u" placeholder="Username" class="form-control" ng-min-length="4" required />
<p ng-show="info.u.$invalid" class="help-block">You username is required.</p>
</div>
<div class="form-group">
<input type="password" name="password" ng-model="info.p" placeholder="Password" class="form-control" />
<p ng-show="info.p.$invalid" class="help-block">password is required.</p>
</div>
<button ng-disabled="loginForm.$invalid" class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</fieldset>
</form>
目前我正在做的是将其传递给函数。但是有没有一种更简洁的方法可以从 Controller 函数内部访问元素?
最佳答案
您可以尝试这样的操作,在 ng-submit 属性中, ng-submit="attempt('...', $event);?>')"传递 $event 参数。但是,不要忘记将其添加到您的函数中,如下所示:
$scope.attempt = function (url, $event) {
//URL get passed.. but i want to fetch it from the form action attribute
var data = {username:$scope.info.u,password:$scope.info.u};
$http.post(ul, data).success(function(response) {
$scope.error = "welcome";
$rootScope.currentUser = data;
session.set('siUser', data);
$location.path('/dash');
}).error(function(reason) {
$scope.error = "failed try again" + $scope.info.p + ' ' + $scope.info.u;
});
};
您将能够像这样获取 angular.element:
angular.element($event.target);
请告诉我此解决方案是否适合您
关于javascript - angularjs访问ngsubmit函数内的表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799486/