Using AngularJS to automatically fill checkboxes during editing

Transitioning from server-side operations to AngularJS for real-time functionality is a new challenge I'm taking on.

With a user who can have multiple permissions, I'm facing an issue when it comes to repopulating checkboxes for permission changes. I'm currently utilizing the checklist-model directives which can be found here

My database setup includes tables for users, permissions, and users_permissions.

In my UsersController (Laravel)

public function show($id)
{
    $user = User::with('permissions')->find($id);
    return $user;
}

In my UserController (Angular)

Users.controller('UserController', ['$scope', '$routeParams', 'User', 'Permission', function($scope, $routeParams, User, Permission) {
    $scope.user = User.get({ id: $routeParams.id });
    $scope.permissions = Permission.query();
}]);

With permissions attached to the user on the server-side, viewing the object using console.log($scope.user) returns the expected output.

View (single-user.html)

   <h4>Manage Permissions</h4>
    <div class="form-group">
        <label ng-repeat="permission in permissions">

        <input type="checkbox" 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>

My attempt to create an assigned variable in the controller containing $scope.user.permissions.id to compare against $scope.permissions.id did not provide the desired results. When I tried

$scope.assigned = $scope.user.permissions.id
and logged it, I only received 'undefined'.

If you have any pointers on creating an array of assigned permissions for comparison with standard permissions, I would greatly appreciate the advice.

Answer №1

User.get and Permission.query seem to be utilizing $resource. These calls will return promises that, if everything goes smoothly, will resolve to your data instead of directly returning the data. Since these calls are asynchronous, you need to provide a function parameter that will be executed once the async operations are finished.

When you encountered undefined during the console.log test, it was because in $scope.user.permissions.id, $scope.user is actually a promise not the object you were anticipating. Essentially, you were evaluating $q.permissions.id, which is undefined.

User.get({ id: $routeParams.id }, function(user) { $scope.user = user; });
Permission.query(function(permissions) { $scope.permissions = permissions; });

Alternatively, you could attempt something like this (although not completely certain):

$q.all(
    User.get({ id: $routeParams.id });
    Permission.query();
).then(function(user, permissions) { $scope.user = user, $scope.permissions = permissions });

For further information on how to chain actions to the User.get() and Permission.query() calls, refer to the following resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring that the text in the Bootstrap navbar is responsive for all screen

Yesterday, I inquired about how to modify my navbar menu to switch from horizontal to vertically arranged depending on layout. However, I've noticed that the responsiveness is not consistent when adjusting the window size. Is there a way to ensure my ...

Converting JavaScript strings into nested arrays

Currently, I am developing my own bi-directional DOM binder to connect input fields to JSON data as a way to enhance my understanding and skills. I have chosen not to use frameworks like Ember, Angular, or KnockoutJS for this project. One challenge I am fa ...

Passing array map data to another screen in React Native

Greetings! I successfully created an array map to showcase specific data from my API. Now, I am faced with the challenge of TRANSFERRING THIS DATA TO ANOTHER SCREEN. My current dilemma lies in the fact that the displayed data is generated using ARRAY MAP, ...

Using Javascript to hide specific rows in a table

Question for Javascript beginners: I am aware that there are numerous ways to achieve this task, many of which are explained on various platforms. However, my question pertains specifically to the following code snippet. <html> <head> <scri ...

Discover identical JSON elements in 2 JSON arrays using JavaScript and add CSS styles to the corresponding items within a UL list

In order to manipulate JSON data using JavaScript, I am required to create an HTML UL list of tags based on a JSON array of Tag items. Furthermore, there is a second set of Tags in another JSON data-set that needs to be compared with the first Tag JSON da ...

Events in Three.js have an impact on the Document Object Model (

Here's a simple question for you. Is it possible to create click events in a three.js scene that can manipulate the DOM? For example, if an object is clicked in the scene, can it make a panel outside the scene become visible? Thank you! ...

Having difficulty entering text into the Material UI TextField

I am encountering an issue with a button that opens up a Material UI Dialog containing a TextField. However, I am unable to click into the TextField to input any text. Additionally, when clicking on the button to open the Dialog, I receive the error messag ...

Issue with the positioning of bootstrap popover after content is added

Having trouble writing a function that adds a textarea to the bottom of a popover content when clicking on a button. The issue is that once the textarea is displayed, the popover extends downward and obscures the text. I'm looking for a solution where ...

Uncheck all boxes except for the required or disabled boxes in Angular

HTML: <mat-selection-list #selectedColumns [(ngModel)] ="selectedOptions"> <div class= "content-section"> <mat-expansion-panel> <mat-expansion-panel-header> ...

JQuery form not triggering the submit event

Currently, I am facing some issues with my code while trying to trigger on submit event on a form and validate it. The main problems I encountered are that the onsubmit event is not being triggered, and the input field of type email is not validated proper ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

angularjs and cakephp working together to handle a request

I've implemented a method in the UsersController to add new users to the database. In the cakephp ctp views, everything seems fine as the request isn't being black-holed and I'm using 'post' for this purpose. However, when I transi ...

Managing traffic in Google Kubernetes Engine (GKE)

I am encountering an issue with our website deployment on GKE, which consists of 10 pods. When deploying a new version, we use MAXsurge=1 and MAXunavailable=0. Upon trying to access the website during a new deployment, I sometimes only see the header in t ...

React application triggers `OnKeyDown` event just once

Hey there! I'm diving into the world of web development and could use some help. My current challenge involves manipulating input data based on key combinations like ctr + ArrowUp (increase) and ctr + ArrowDown (decrease). The dynamic part should be h ...

Discovering the regex pattern to locate any existing code and substitute it with nothing

How do I remove possible code from strings and replace it with blank? For example: Input = 9eac83a4-80f4-4a2e-b0fe-7a4a9329ff62Manual Handling.pdf Desired Output = Manual Handling.pdf Input = 14a19827-8f33-4666-a3cc-ea257875f1f7Fire&Evac.pdf Desir ...

Is there a way to retrieve $httpProvider.defaults.xsrfCookieName within .factory?

Here's a question that might come from someone new to programming. I'm trying to avoid hard-coding the values for xsrfHeaderName and xsrfCookieName. Can anyone guide me on how to retrieve them from the $httpProvider? .factory('XSRFIntercept ...

It seems like the method has already been executed despite encountering an unexpected end of JSON input error

Currently, I am utilizing the etherscan API to retrieve logs for certain events. Although my JSON parsing method seems quite traditional, an error is being thrown stating "unexpected end of JSON". function getEventHistory() { const topic0 = web3.util ...

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

A step-by-step guide on generating a single chip using the same word in Angular

I'm trying to find a solution to ensure that only one chip is created from the same word inputted, instead of generating duplicates. Currently, users can input variations such as "apple," "APPLE," "apPPle," "aPpLe," and I want to automatically conver ...