使用AngularJS提交表单的正确方法是什么?

时间:2015-01-12 00:11:37

标签: javascript angularjs forms

所以我正在写一个表单,我正在编写提交函数。此提交函数应检查表单是否有效,将其POST到服务器,然后在收到响应时使用ui-router更改状态。

所有相当简单的东西,虽然它让我思考。在AngularJS的大多数示例中,我看到以下内容:

$scope.submit = function() {
    var params = { someKey: $scope.someKey };
    $http.post(...);
};

对我来说,这似乎是向后的..这不会$scope.submit$scope ergo的当前状态产生那么难以测试吗?

我最近在这些方面写了一些东西:

$scope.submit = function(params) {
    // Any sanity checking, such as checking various parameters exist
    if(angular.isUndefined(params.summonerName)) {
        throwToysOutOfPram();
        return;
    }
    $http.post(...);
};

然后在视图中,我有类似的东西:

<button ng-click='submit({ summonerName: summonerName, twitchName: twitchName })'>Submit</button>

对我来说,这似乎从可测试性POV中最有意义,但我认为在视图中放置“逻辑”感觉很糟糕。什么是普遍的共识?


AddStreamerCtrl

angular.module('project.streamers')
.controller('AddStreamerCtrl', ['$scope', 'channelName', 'Streamer', 'regions', 'languages', function ($scope, channelName, Streamer, regions, languages) {
    $scope.channelName = channelName;
    $scope.regions = regions;
    $scope.languages = languages;

    $scope.submit = function(params) {
        Streamer.save(params, function() {
            console.log('it worked!');
        }, function() { 
            console.error('something went wrong :(');
        });
    };
}]);

streamers.add州设置

angular.module('project.streamers')
.config(['$stateProvider', function ($stateProvider) {
    $stateProvider.state('streamers.add', {
        templateUrl: '/streamers/create.html',
        url: '/add',
        params: {
            channelName: null,
        },
        controller: 'AddStreamerCtrl',
        resolve: {
            channelName: function($stateParams) {
                return $stateParams.channelName;
            },
            languages: function(Language) {
                return Language.get();
            },
            regions: function(Region) {
                return Region.get();
            }
        }
    }); 
}]);

create.html上

<h1>Streamer Sign Up</h1>
<p>This form will guide you through the steps of adding your stream to our list. In order to qualify, you must have a valid League of Legends and Twitch account.</p>

<p class='panel callout'>Please note that the administrators of this website reserve the right to remove your stream at their discretion.</p>

<form name='addStreamerForm' ng-submit='submit(data)'>
    <label>Twitch Channel 
        <input type="text" ng-model='data.channelName' name="channelName" placeholder="Channel Name" required>
    </label>
    <p>This is your Twitch username. For example, if your url is <code>twitch.tv/aredherring</code>, then your username would be <code>aredherring</code>.</p>

    <label>Language
        <select ng-options='language.id as language.name for language in languages' ng-model='data.language' required>
            <option value=''>Select a language</option>
        </select>
    </label>
    <p>This is the language you stream in. If you are multi-lingual, please select the language you will use most often.</p>

    <label>Region 
        <select ng-options='region.id as region.name for region in regions' ng-model='data.region' required>
            <option value=''>Select a region</option>
        </select>
    </label>
    <p>This is the region your League of Legends account is on. If you have accounts on multiple regions, select the region you are most likely to play on on a day-to-day basis.</p>

    <label>Summoner Name
        <input type="text" name="summonerName" ng-model='data.summonerName' placeholder="Summoner Name" required>
    </label>
    <p>This is your summoner name for your League of Legends account. If you have multiple accounts, specify the account that you use most often.</p>

    <p>We will use the League of Legends API and Twitch API to retrieve data about your accounts.</p>


    <label>
        <input type="checkbox" name="tAndCs">
        I agree to the <a ui-sref='termsAndConditions'>Terms and Conditions</a>
    </label>

    <input type='submit' class='button' value='Submit'>
</form>

1 个答案:

答案 0 :(得分:0)

为了在软件开发中保持低coupling和高cohesion,通常最好将功能与其操作的数据分开,因此它可以用于更多比一个数据集的实例。在这种情况下,是的,您在上面概述的第二种方法更为可取,因为它与附加到$scope的特定变量无关。

假设你有ng-model="data.summonerName"ng-model="data.twitchName",你可以这样做:

<button ng-click='submit(data)'>Submit</button>

这样,如果您稍后发现(例如)您需要能够从代码本身(或某些unit-testing代码)调用submit,您可以非常轻松地执行此操作:

$scope.submit({summonerName: testSummonerName, twitchName: testTwitchName});

使用原始方法,您必须对$scope属性进行一些时髦的操作。

此外,使用Angular,表单验证几乎可以在标记中完成,并提供对用户输入的即时响应(请参阅 forms guide )。

  

请记住,虽然客户端验证起着重要作用   在提供良好的用户体验方面,它可以很容易地被规避和   因此不可信任。服务器端验证仍然是必需的   一个安全的应用程序。