What is the best way to enable a service to retrieve variables from the Controller?

My controller has variables declared on the $scope and two arrays that hold objects: one for available groups and the other for groups the user is already a part of. The addUserToGroups() function sends a call to the server to add the user to the selected groups. However, I encounter an error stating that the assignedGroups array is undefined when I try to update the DOM to reflect the changes.

Controller:

spApp.controller('userCtrl', 
    function userCtrl($scope,userService,groupService){
        $scope.users = userService.getUsers();
        $scope.selectedAvailableGroups;
        $scope.selectedAssignedGroups;
        $scope.availableGroups;
        $scope.assignedGroups;
        $scope.selectedUser = false;

        $scope.addUserToGroup = function (){
            userService.addUserToGroup($scope.selectedUser, $scope.selectedAvailableGroups)
        };
    });

I pass objects into the controller function for the service to use. While it works, I wonder if this is the best approach or if I'm creating too many global variables within the controller.

Service:

spApp.factory('userService', function(){
  var addUserToGroup = function (selectedUser, selectedAvailableGroups) {
    var addToGroupPromises = [];
    var selectedGroupsLength = selectedAvailableGroups.length

    for (var i = 0; i < selectedGroupsLength; i++) {
      addToGroupPromises[i] = $().SPServices({
        operation: "AddUserToGroup",
        groupName: selectedAvailableGroups[i].name,
        userLoginName: selectedUser.domain
      });      
    };

    $.when.apply($,addToGroupPromises).done(function (){
      for (var i = 0; i < selectedGroupsLength; i++) {
        assignedGroups.push(selectedAvailableGroups[i]);
      };
      alert(selectedUser.name + " added to: " + JSON.stringify(selectedAvailableGroups));  
    });   
  };     
});

HTML:

<button type="button" ng-disabled="!selectedUser" ng-click="addUserToGroup()">Add User</button>

I am new to Angular and seeking the best way to handle this. Thank you.

EDIT: I tried passing the $scope.assignedGroups into the function, which works, but the DOM doesn't update even though ng-options should be listening for changes. I can see the assignedGroups change in Batarang, but the DOM doesn't reflect it.

<select id="entityAssigned" multiple
    ng-model="selectedAssignedGroups" 
    ng-options="g.name for g in assignedGroups | orderBy:'name'">                       
</select>

Answer №1

Here are some example codes to demonstrate the concept.

In essence, you are informing angular that you intend to utilize $scope in your service.

   _app.services.MyService = function ($scope) {
         var updateProfile = function (selectedUser, selectedDetails) {
             var userProfiles = $scope.userProfiles;
         }
    }

    _app.services.MyService.$inject = ['$scope'];

I hope this explanation is beneficial to you.

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

How do I customize the time range for the weekly schedule on fullcalendar to show only from 9:00 AM to 6:00 PM instead of the default 0:00 to

Calendar by AngularUI and FullCalendar by Arshaw I am currently utilizing the ui-calendar for my project. However, I am facing an issue where the weekly times are showing all 24 hours of the day. Is there a way to adjust the settings so that it only displ ...

The presence of certain characters is leading to problems in the console

Similar Question: Escaping a String for JavaScript Usage in PHP? The characters in my text are causing errors. When I input special characters such as: !\"$%^&()-=\'.,:;/?#~/\\>< An error saying "Syntax error ...

Utilize React Native to continuously fetch and display data from this API

[React-Native] Seeking assistance on looping through JSON API for conditional rendering. As a beginner, I would greatly appreciate your guidance. Thank you. Find my code here: https://drive.google.com/file/d/0B3x6OW2-ZXs6SGgxWmtFTFRHV00/view Check out th ...

Adjust the existing percentage of a never-ending CSS animation

I am looking to create a simple slider from scratch. The sliding functionality is working perfectly in an infinite loop, but I want to add the option for users to skip to specific slides (e.g. using arrows). @keyframes slider-ani { 0% { left: 33.3%; } ...

The data within an isolated scope is failing to appear in the template of the directive

I am currently working on a custom Angular directive that is designed to showcase pagination throughout my application. Despite using an isolated scope to pass the parameter totalNoOfRecords, I am facing issues with it not being displayed. Any assistance ...

The React Native app mysteriously crashes repeatedly without generating any error logs when using the same component multiple

Currently, I am developing in React Native app Version 0.70. Encountering a peculiar issue where the React Native app crashes without any error logs in the console. Below is the snippet of my code where most crashes seem to happen: import { ...

Redirecting JavaScript form to search engine

I am struggling with creating a form that enables a user to input text and then directs them to a specified search engine with the input as the query. I am encountering difficulties in getting the JavaScript to properly redirect. An interesting observatio ...

Tips on implementing Piwik JavaScript code within app.js on Express

I am trying to implement Piwik tracking on my Express website using JavaScript code. I placed the code in my app.js file but encountered an error. Here is the JavaScript code snippet: <script type="text/javascript"> var _paq = _paq || []; ...

What is the best way to retrieve information from an array containing objects in AngularJS?

Check out this json data: { topalbums: { album: [ { name: "The Very Best of Cher", playcount: 1634402, mbid: "a7e2dad7-e733-4bee-9db1-b31e3183eaf5", url: "http://www.last.fm/music/Cher/The+Very+Bes ...

Exporting Data from AngularJS UI-Grid to Excel: A Step-by-Step Guide

Hey there, I'm just starting out with angularJS and I have a question. Is it possible to export my ui-grid data to an excel file, with each value in its own cell? If so, how can I achieve this? Are there any examples or tutorials available that could ...

Is it possible to apply styles to javascript elements without relying on img class? Additionally, how can I incorporate an onclick button while maintaining a fully functional navigation bar?

My current project involves creating an interactive collage where users can click around and have pictures pop up at the clicked location. The functionality works as intended, but now I'm facing issues with the navigation bar not being clickable. Addi ...

What is the best way to integrate my custom JavaScript code into my WordPress theme, specifically Understrap?

I am looking to enhance my website with a sticky navbar positioned directly under the header, and I want it to stick to the top of the page as users scroll down. Additionally, I want the header to disappear smoothly as the user scrolls towards the navbar. ...

Why do all the cards suddenly come to life when I press the activate button on just one card?

Whenever I try to activate a specific card by clicking the active button, all the cards end up getting activated. I have used the className variable and manually set it to "card mb-3 border-3". My intention is for the className to change when clicking th ...

Prevent vertical scrolling on touch devices when using the Owl Carousel plugin

Is there a way to prevent vertical scrolling on Owl Carousel when dragging it horizontally on touch devices? It currently allows for up and down movement, causing the whole page to jiggle. If anyone has a solution, I can share the JavaScript file. Appreci ...

A guide on populating a dropdown menu with spring and hibernate in JSP

I'm a newcomer here and seeking ideas from you all. I have 4 dropdown lists and want to populate one select box based on the selection made in another select box using database values. I have already set up the database, but unsure how to proceed. Any ...

Leverage React Context beyond the confines of a React component

The React Context API has impressed me, but I often find myself struggling to access it outside of a React component. Everything works smoothly within a React function or class component, but when it comes to fetching a value from the context for tasks lik ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

I am receiving all NFT IDs when I should only be getting the ones that are associated with the current account

I am facing an issue where I am receiving all NFTs token IDs instead of just the one that belongs to the current account. The code snippet causing this problem is as follows: const { enableWeb3, account, isWeb3Enabled, Moralis, deactivateWeb3 } = useMorali ...

Issue: encountered a write EPIPE error while attempting to transfer a file to FTP via gulp

Whenever I try to deploy some stylesheets to a server using FTP, I encounter an error about 80% of the time. Here's the specific error message: Error: write EPIPE at _errnoException (util.js:1022:11) at WriteWrap.afterWrite [as oncomplete] (net.j ...