1

I'm having trouble rendering dynamic checkboxes with JSON API response.

This 2 ng-repeats:

  1. Bringing the listing of categories in BD, and;
  2. ng-model with the selected category listing.

Below my HTML code;

<ul class="list-group">
    <li class="list-group-item" ng-repeat="cats in categorias">
        <div class="checkbox"><label><input type="checkbox" ng-model="checkbox[item.cats]"><span class="checkbox-material"><span class="check"></span></span></label> {{cats.name}}</div>
    </li>
</ul>

JSON/API response (1)

[
  {"id":"1","id_module":"1","name":"Esportes"},
  {"id":"2","id_module":"1","name":"Entretenimento"},
  {"id":"3","id_module":"1","name":"Terror"},
  {"id":"4","id_module":"1","name":"Drama"}
]

JSON response (2)

{cats":["1","2"]}

I would like that the checkbox stay checked with the response.

Does anyone have any idea?

3
  • 1
    If i'm understanding your use case, what you want is to write a function that receives the value to find in Json2. In that function, iterate the Json2 array and return true if the value is matched and false otherwise. Call this function from Angular's ngChecked directive. Also, since a checkbox only represents boolean values, you should assign the desired checked value to the model with Angular's ngValue directive. Commented Jun 26, 2015 at 20:39
  • Can you explain what you want exactly in fiddle Commented Jun 26, 2015 at 20:54
  • this example: jsfiddle.net/1t142Lbo Commented Jun 26, 2015 at 21:04

1 Answer 1

2

Here you have working fiddle, check it

jsfiddle.net/b895j3ay

var app = angular.module("Application", [])
app.controller('Ctrl', function($scope) {
  $scope.roles = [{
    id: 1,
    text: 'guest'
  }, {
    id: 2,
    text: 'user'
  }, {
    id: 3,
    text: 'customer'
  }, {
    id: 4,
    text: 'admin'
  }];
  $scope.isChecked = function(id, matches) {
    var isChecked = false;
    angular.forEach(matches, function(match) {
      if (match === id) {
        isChecked = true;
      }
    });
    return isChecked;
  }
  $scope.user = {
    roles: [2, 4, 3]
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="Application">
  <div ng-controller="Ctrl">
    <label ng-repeat="role in roles">
      <input type="checkbox" ng-model="user.roles" checklist-value="role.id" ng-checked="isChecked(role.id,user.roles)">{{role.text}}
    </label>
  </div>
</div>
</div>

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

1 Comment

Thanks, worked on page load, but I forgot I have to add ng-model, for sending the API and if i click the checkboxes, all are checked.

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.