JSFiddle - React, Tailwind, and code Playground

by Thunder Hemlock

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.allComments = [
	{
		"id" : 1,
		"name" : "ROLE_USER",
        selected: false,
	},
	{
		"id" : 2,
		"name" : "ROLE_ADMIN",
         selected: false,
	},
	{
		"id" : 3,
		"name" : "ROLE_READ",
         selected: false,
	},
	{
		"id" : 4,
		"name" : "ROLE_WRITE",
         selected: false,
	} ];


	$scope.selectedComments = [];
    

	$scope.toggleSelection = function toggleSelection(comment)
	{
		var index = $scope.selectedComments.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);
		}
	};
}