anilCSE anilCSE - 4 months ago 34
AngularJS Question

How to update ng-model dynamically in ng-repeat?

I am facing some problem with dynamic ng-model values in my angular page. Here is my sample JSON.

mytabs = [
{
name : "tab1",
values : [
{value:"value1"},
{value:"value2"},
{value:"value3"},
{value:"value4"}
]
},
{
name : "tab2",
values : [
{value:"value1"},
{value:"value2"},
{value:"value3"},
{value:"value4"}
]
}
]


What I want to do from this josn is, creating a view in my page such that, It will contain
tab1
and
tab2
as headings of page and the respective
value
as a
checkbox
. The user will have the selectivity to select his option. On submit I want to get the options he selected. I want to know something like
value1,value3 (frome tab1)
,
value1,value2(from tab2)
are selected, in my controller. How can I do this?

Here is my sample approach.

<div ng-repeat="tab in mytabs">
<h1>{{tab.name}}</h1>
<div ng-repeat="val in tab.values">
<input type="checkbox" ng-model="val.value"/>
</div>
</div>
<input type="button" value="submit" ng-click="checkValues(val)"


Please help me,

Thank you

Answer

You should modify you code a little bit you should add a checked property in the object and bind checkbox to that model .

Kindly could use the below idea or code to get what you want more closely

 <div ng-repeat="tab in mytabs">
  <h1>{{tab.name}}</h1>
    <div ng-repeat="val in tab.values">
        <input type="checkbox" ng-model="val.checked"/>
    </div>
</div>
<input type="button" ng-click="checkValues()" value="checkitems" />

    <script>
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', function ($scope,$filter) {
            $scope.mytabs = [
                {
                    name: "tab1",
                    values: [
                        { value: "value1",checked:false },
                        { value: "value2", checked: false },
                        { value: "value3", checked: false },
                        { value: "value4", checked: false }
                    ]
                },
                {
                    name: "tab2",
                    values: [
                       { value: "value1", checked: false },
                       { value: "value2", checked: false },
                       { value: "value3", checked: false },
                       { value: "value4", checked: false }
                   ]
                }
            ];

            $scope.checkValues = function () {
                angular.forEach($scope.mytabs, function (value, index) {
                    var selectedItems = $filter('filter')(value.values, { checked: true });
                    angular.forEach(selectedItems, function (value, index) {
                        alert(value.value);
                    });

                });
            };
        });
Comments