2

我在 Angularjs 应用程序中工作,我有一个简单的表单。我需要创建一种简单的方法来获取所有表单数据,比如 jQuery 序列化。但我认为数据绑定不是一个好的解决方案。我的表单会有一些像这样的“字段”:

<div class="multiselect-container" >
<label>Countries:</label>
<ul>
    <li ng-repeat="country in countries" >
        <input type="checkbox" id="country_{{country.id}}"  value="{{country.id}}" />
        <label for="country_{{country.id}}"  >{{ country.name }}</label>
    </li>
</ul>

每个“字段”都可以选择一组元素。谁能告诉我一个解决implement()的好方法。

谢谢!

4

3 回答 3

1

我认为数据绑定不是一个糟糕的解决方案,无论如何您可以使用自定义指令来序列化您的数据并将其设置为您指定的属性的值:

function MC($scope) {
    $scope.$watch('prop', function (v) {
        console.log(v);
    });
}

angular.module('ng')
.directive('formSerialization', function () {
    return {
        scope: {
            'formSerialization': '='
        },
        link: function (scope, elem, attrs) {
            console.log(attrs);
            $(elem).closest('form').submit(function () {
                var form = this;
                scope.$apply(function () {
                    scope.formSerialization = $(form).serialize();
                });
            });
        }
    };
});

您可以将其与以下标记一起使用:

<form ng-app="" ng-controller="MC">
    <input name="txt" type="text" ng-model="prop" />
    <input data-form-serialization="prop" type="submit" value="Submit" />
</form>

这是一个 JSFiddle演示

于 2013-11-03T21:28:44.603 回答
1

你可以试试这个,http://docs.angularjs.org/api/ng/function/angular.toJson

通过这种方式,您可以将对象序列化为 json 字符串

于 2014-03-13T09:36:22.150 回答
1

感谢您的回答。对不起,我没有很好地公开我的问题,但我找到了一个简单的解决方案。

<div class="multiselect-container" >
    <label>Countries:</label>
    <ul>
        <li ng-repeat="country in countries" >
           <input type="checkbox" id="country_{{country.id}}" ng-model="data.countries[country.id]"  value="{{country.id}}" />
           <label for="country_{{country.id}}"  >{{ country.name }}</label>
        </li>
    </ul>
</div>

谢谢!

于 2013-11-04T21:03:43.840 回答