angularjs访问ngsubmit函数中的表单元素

时间:2015-03-01 21:44:05

标签: javascript jquery angularjs

如何访问在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>

目前我正在做的是将它传递给函数。但是有更清晰的方法从控制器功能内部访问元素吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用ng-submit属性,ng-submit =&#34;尝试(&#39; ...&#39;,$ event);?&gt;&#39; )&#34;传递$ 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);

如果此解决方案适合您,请告诉我