2013-11-03 66 views
1

我正在Angularjs應用程序中工作,並且我有一個簡單的表單。我需要創建一個簡單的方法來獲取所有表單數據,比如jQuery序列化。但我的數據綁定不是一個好的解決方案。我form'll有一些「場」是這樣的:Angularjs相當於序列化

<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> 

每一個「場」我一個可以選擇一組元素。有人可以告訴我一個很好的解決方法()的方法。

謝謝!

+2

爲什麼你認爲數據綁定是不是一個好的解決方案嗎? –

+0

那麼,沒有使用AngularJS的前臺經驗。你如何實現這樣的例子? –

+1

使用Angular,您應該停止思考DOM並根據模型進行思考。因此,將表示數據的對象放在$ scope中,將輸入綁定到該對象,然後提交該對象。 –

回答

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 DEMO

+0

如果你必須使用序列化,我會說你最好將角度表單數據對象傳遞給jquery的'param'全局靜態方法:http://api.jquery。 COM/jquery.param / – marksyzm

0

謝謝你的答案。我不會以很好的方式揭露我的問題,但我找到了一個簡單的解決方案。

<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> 

謝謝!