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

What's the correct way to submit a form using AngularJS?

所以我正在编写一个表单,目前正在编写提交功能。此提交功能应检查表单是否有效,POST 将其发送到服务器,然后在收到响应时使用 ui-router.

更改状态

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

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

对我来说,这似乎倒退了..这对夫妇 $scope.submit 是否严重影响了 $scope 的当前状态,因此很难(呃)测试?

我最近写了一些类似这样的东西:

$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 来看,这似乎最有意义,但我有一部分人对将 'logic' 放在视图中感觉很糟糕。普遍共识是什么?


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>

为了在软件开发中保持低 coupling and high cohesion,将功能与其操作的数据尽可能分离通常是一种很好的做法,因此它可以用于多个实例数据集。在这种情况下,是的,您上面概述的第二种方法更可取,因为它不依赖于附加到 $scope.

的特定变量

假设您有 ng-model="data.summonerName"ng-model="data.twitchName",您可以:

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

这样,如果您稍后发现(例如)您需要能够从代码本身(或某些 unit-testing 代码)调用提交,您可以很容易地做到这一点:

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

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

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

Keep in mind that while client-side validation plays an important role in providing good user experience, it can easily be circumvented and thus can not be trusted. Server-side validation is still necessary for a secure application.