1

I am trying to repopulate a group of checkboxes based on user permissions that have previously been selected.

I created an array of the permission id's and want to compare the input element to the array of id's and display the checkbox as checked if they there is a match, otherwise display an unchecked checkbox.

This is how I created the $scope.assigned array:

$scope.user.$promise.then(function(result) {
    $scope.user = result;
    $scope.assigned = [];
    angular.forEach($scope.user.permissions, function(value, key) {
        this.push(value.id);
    }, $scope.assigned);

console.log($scope.assigned);

When the $scope.assigned is logged to the console, I am left with an array such as ["2", "3", "4"] representing the previously selected permission ids. Now I want to compare those to the permissions.id

the view:

<h4>Manage Permissions</h4>
<div class="form-group" ng-repeat="permission in permissions">
    <label>
        <input ng-if="permission.id == assigned" type="checkbox" ng-checked="true" checklist-model="user.permissions" checklist-value="permission.id" class="checkbox-inline">
        {{ permission.display_name }}
    </label>
</div>
<button class="btn btn-success" type="submit">Save</button>

I thought that I could do something like ng-if="permission.id == assigned" but that does not work. I need a way to check if permission.id matches anything inside of assigned.

I previously did this in PHP like this: if(in_array($permission['id'], $assigned))

How can I accomplish this in AngularJS? Thanks for any advice.

1 Answer 1

0

Use indexOf:

ng-if="assigned.indexOf(permission.id) != -1"
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thanks @merlin! Didn't know about indexOf(), I'm still very new to JavaScript and AngularJS. Appreciate the help!
@MitchGlenn Also take a look at the compatibility table of Array.prototype.indexOf if you want to support old browsers.

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.