0

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

2
  • Your API returns 1 object. This object should be the checkbox checked. It that right? Commented Jan 18, 2017 at 9:02
  • @Mistalis yes. The name of the item that should be selected on init. Only the name Commented Jan 18, 2017 at 9:08

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Now i try, i'll let you know. Thank you in the while

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.