JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="">
<div ng-controller="TestController">
<p ng-repeat="permission in allPermissions">
<input type="checkbox" ng-checked="selectedPermissions.containsObjectWithProperty('id', permission.id)" ng-click="toggleSelection(permission)" />
{{permission.name}}
</p>
<hr />
<p><b>All:</b> | <span ng-repeat="permission in allPermissions">{{permission.name}} | </span></p>
<p><b>Selected:</b> | <span ng-repeat="permission in selectedPermissions">{{permission.name}} | </span></p>
</div>
</div>
JavaScript
/**
* Searches an array for an object with a specified property.
*
* Example usage:
* <code>var index = myArray.indexOfObjectWithProperty('id', 123);</code>
*
* @param propertyName the name of the property to inspect
* @param propertyValue the value to match
* @returns the (zero-based) index at which the object was found, or -1 if no
* such object was found
*/
Array.prototype.indexOfObjectWithProperty = function(propertyName, propertyValue)
{
for (var i = 0, len = this.length; i < len; i++)
{
if (this[i][propertyName] === propertyValue) return i;
}
return -1;
};
/**
* Test if an array of objects contains an object with a specified property.
*
* Example usage:
* <code>var isPresent = myArray.containsObjectWithProperty('id', 123);</code>
*
* @param propertyName the name of the property to inspect
* @param propertyValue the value to match
* @returns true if an object was found, false otherwise
*/
Array.prototype.containsObjectWithProperty = function(propertyName, propertyValue)
{
return this.indexOfObjectWithProperty(propertyName, propertyValue) != -1;
};
function TestController($scope)
{
$scope.allPermissions = [
{
"id" : 1,
"name" : "ROLE_USER"
},
{
"id" : 2,
"name" : "ROLE_ADMIN"
},
{
"id" : 3,
"name" : "ROLE_READ"
},
{
"id" : 4,
"name" : "ROLE_WRITE"
} ];
$scope.selectedPermissions = [
{
"id" : 1,
"name" : "ROLE_USER"
},
{
"id" : 3,
"name" : "ROLE_READ"
} ];
$scope.toggleSelection = function toggleSelection(permission)
{
var index = $scope.selectedPermissions.indexOfObjectWithProperty('id', permission.id);
if (index > -1)
{
// Is currently selected, so remove it
$scope.selectedPermissions.splice(index, 1);
}
else
{
// Is currently unselected, so add it
$scope.selectedPermissions.push(permission);
}
};
}