FarazShuja
FarazShuja

Reputation: 2370

angularjs way of getting form values in comma seperated values

I have a form like this

<form id="myForm">
    <input type="text" name="userName" value="test" />
    <ul>
      <li ng-repeat="item in list">
            <input type="checkbox" name="chkList" value="id" />
      </li>
    </ul>
</form>

I am using jquery to submit form and converting the post data like this

var d = 'name=' + $('#myform input[name=userName]).val();
var valArr = [];
$('#myform input[name=chkList]').each(function() {
    valArray.push($(this).val());
});
d = '&listOfIds=' + valArray.join(',');
... then submitting post with data: d

I dont want to use jquery but not sure what the angualr equivalent would be here?

Upvotes: 0

Views: 55

Answers (2)

Jevgeni
Jevgeni

Reputation: 2574

Here is what your are looking for: JSFiddle

HTML

<div ng-app="myApp" ng-strict-di>
<div ng-controller="Ctrl">
    <div ng-repeat="item in items">
        <input type="checkbox" ng-model="$parent.values[item.id]"/>{{item.name}}
    </div>
    <button type="button" ng-click="submit()">Submit</button>
</div>

JS:

angular.module("myApp",[]).controller("Ctrl",function($scope){

    angular.extend($scope,{
        values:{},
        items:[
            {id:1,name:'name1'},
            {id:2,name:'name2'},
            {id:3,name:'name3'},
            ],
        submit: function() {
            var d = '&listOfIds=' + Object.keys($scope.values).join(",");
            alert(d);

        }
    });
});

Upvotes: 0

Stepan Suvorov
Stepan Suvorov

Reputation: 26156

actually it's all in details, it could be so:

 <input type="checkbox" name="chkList" ng-model="valArray[$index]" value="id" />

and in the controller:

 $scope.valArray = [ 1 , 2 , 3 ];

Upvotes: 1

Related Questions