1

I have two arrays coming from web service of object. One is all categories and other one is selected categories like this

$scope.categories = [
    { "id": 1, "name": "cat1" },
    { "id": 2, "name": "cat2" },     
    { "id": 3, "name": "cat3" }, 
    { "id": 4, "name": "cat4" }
];

$scope.selected_category = [
    { "id": 1, "name": "cat1" },
    { "id": 2, "name": "cat2" }
];

and my markup is like this

<div class="form-group">
    <label>Category</label>
    <div class="clr"></div>
    <label class="checkbox-inline" ng-repeat="item in categories">
        <input type="checkbox" value="{{item.id}}" ng-model="?" ng-checked="?">         
        {{item.name}}
    </label>
</div>

I can't figure out how do I check those checkboxes which are coming as selected. please help!

Thanks

1
  • add checked property to categories, and then use that to manage checked unchecked objects... Commented Feb 11, 2015 at 9:42

2 Answers 2

0

I think your $scope.categories should be updated that way :

$scope.categories = [
  { "id": 1, "name": "cat1", "isSelected": false },
  { "id": 2, "name": "cat2", "isSelected": false  },     
  { "id": 3, "name": "cat3", "isSelected": false  }, 
  { "id": 4, "name": "cat4", "isSelected": false  }
];

And use it that way :

<div class="form-group">
  <label>Category</label>
  <div class="clr"></div>
  <label class="checkbox-inline" ng-repeat="item in categories">
    <input type="checkbox" value="{{item.id}}" ng-model="item.isSelected">         
    {{item.name}}
  </label>
</div>

ng-model will take care of selecting or not the checkbox for you

If you really need to have an object with selected categories, you also can do this :

$scope.$watch("categories", function(oldVal, newVal){
    //Create your object here
});
Sign up to request clarification or add additional context in comments.

Comments

0

There are two approaches for your question.

  1. You can call a function with ng-checked="checkSelected(item.id)".Pass the id in the function.Then in the controller compare this with the id of the $scope.selected_category array and return those id's that match the array
  2. You can write a condition directly in ng-checked directive (This is applicable only if your data is not too big).You can find more about this approach here example

Comments

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.