javascriptjqueryangularjscheckboxng-init

Init checkbox angularjs on ng-repeat


I've got this situation:

<md-subheader class="md-no-sticky">
            <span data-ng-if="itemSelected == undefined || itemSelected == ''">Choose</span>
            <span data-ng-if="itemSelected != '' || itemSelected != undefined">{{itemSelected}}</span>
        </md-subheader>
        <md-list-item ng-repeat="item in items">
            <p> {{item.name}} </p>
            <md-checkbox class="md-secondary" ng-init="itemSelection" ng-model="itemSelection" ng-change="changeItemSelected(item)"></md-checkbox>
        </md-list-item>

In which i've got a list of items that you can select using a checkbox. The function on ng-change is this:

$scope.changeItemSelected = function(item) {
        $scope.itemSelected = item.name;
    };

When the controller starts, I call a service that get the data checked before. So if the data is not undefined (it means that before something was checked) I set this itemSelection as true. As you can see this variable is used on ng-init. It's working, but not too much. In this way it selects all the checkboxes and not the one i want. I can't reproduce the init call. I created a jsfiddle with this situation by the way http://jsfiddle.net/2f6qscrp/225/ try to think that when the jsfiddle starts it fires a call to the server to get one of the item selected before. For example i want select the third item of the list. because the server returns the third data like this:

{"data":{orange},"meta":{"code":200}}

something like that


Solution

  • Here I had a function checkItem() call in ng-init:

    <md-checkbox class="md-secondary" ng-init="checkItem(item)" 
                                      ng-model="item.checked"                        
                                      ng-change="changeItemSelected(item)">
    </md-checkbox>
    

    This function checks if a checkbox name correspond to the object returned from your server:

    $scope.srvValue = { // Value from your server
        "data": "orange",
        "meta": {"code": 200}
    };
    
    $scope.checkItem = function(item) {
        if (item.name == $scope.srvValue.data) { // It matchs!
            item.checked = true;
            $scope.changeItemSelected(item);
        }
        else item.checked = false; // It does not
    };
    

    JSFiddle demo