Rob
Rob

Reputation: 7216

Passing an array in a hidden input

I'm attempting to pass an array of values in a hidden input using angular. Here is my code so far:

<input type="hidden" name="drug[drug_class_ids][]" value="{{selectedDrugClassIds()}}"/>

where

$scope.selectedDrugClassIds = function ()
{
    var selected_drug_class_ids = [];
    for (var x in $scope.selected_drug_classes)
    {
        selected_drug_class = $scope.selected_drug_classes[x];
        console.log(selected_drug_class);
        selected_drug_class_ids.push(selected_drug_class.id);
    }

    return selected_drug_class_ids;
};

But this is giving me the incorrect

"drug_class_ids"=>["[15,5,8]"]

Where I need

"drug_class_ids"=>["15", "5", "8"]

Any ideas how I could fix this?

Upvotes: 1

Views: 1125

Answers (2)

Gecko
Gecko

Reputation: 1344

I think this is because angular stores the array as a string in the hidden field instead of the actual array. So just stringify it to json in angular and decode it in back end.

Upvotes: 0

Rob
Rob

Reputation: 7216

Got it!

This was an interesting one:

    <div ng-repeat="drug_class in selected_drug_classes">
      <input type="hidden" name="drug[drug_class_ids][]" value="{{drug_class.id}}"/>
    </div>

Upvotes: 1

Related Questions