transferring id values between controllers in angularJS

How can I pass an id from one controller to another in Angular? I have a select menu that allows for selecting a tournament, and upon selection, I want to retrieve the tournament’s _id value in a different controller to query data. Being new to Angular, any guidance would be highly appreciated. Thank you!

Select Menu

<select class="form-control" ng-model="vm.selectedTournamentId" ng-change="vm.showTournament()" >
  <option value="">Select a tournament</option>
  <option ng-repeat="tournament in vm.tournaments" value="{{ tournament._id }}">{{ tournament.name }}</option>
</select>

app.js

.controller('NavigationController', NavigationController);
NavigationController.$inject = ['TournamentService', '$q', '$location', '$scope', '$filter', '$state'];
function NavigationController(TournamentService, $q, $location, $scope,  $filter, $state) {
  var vm = this;
  vm.tournaments = TournamentService.query();
  vm.showTournament = function() {
    var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
    vm.selectedTournament = tournament[0]
    $state.go('dashboard.tournament')
    });
  }
}

dashboard.js

angular.module('Dashboard',[]).controller('DashboardController',
DashboardController).factory('TournamentService', TournamentService).factory('UserService', UserService).factory('TeamService', TeamService)

DashboardController.$inject = ['$scope','TournamentService','TeamService','UserService','$q'];

function DashboardController($scope, TournamentService, TeamService, UserService, $q) {
  var vm = this;
  var tournaments = TournamentService.query();
  var users = UserService.query();
  var teams = TeamService.query()

  $q.all([tournaments, users, teams]).then(function(results) {
    vm.users = users;
    vm.availablePlayers = users;
    vm.tournaments = tournaments;
    vm.teams = teams;
  })
}
TournamentService.$inject = ['$resource'];
  function TournamentService($resource) {
   return $resource('/api/tournaments/:id',{cache: true},{tournament: '@tournament'});
  }
UserService.$inject = ['$resource'];
  function UserService($resource) {
  return $resource('/api/users/:id', {cache: true},{user: '@user'})
}
TeamService.$inject = ['$resource'];
  function TeamService($resource) {
  return $resource('/api/teams/:id',{cache: true}, {team: '@team'})
}

})();

Answer №1

When working with ui-router, it is recommended to utilize $stateParams for handling parameters.

Consider the following scenario:

  vm.showTournament = function() {
    var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
    vm.selectedTournament = tournament[0]
    $state.go('dashboard.tournament')
    });
  }

Modify it like this:

  vm.showTournament = function() {
    var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
        vm.selectedTournament = tournament[0];
        $state.go('dashboard.tournament', {tournamentId: vm.selectedTournamentId});
    });
  }

The key change lies in the $state.go. Now an object with a property of tournamentId is included, which holds the selected tournament id. This property will be passed to the next state, which is dashboard.tournament.

In the second controller, inject $stateParams and access the tournament property using $stateParams.tournamentId, assigning it something like

vm.tournament = $stateParams.tournamentId
.


To make this work, add a parameter to the state where you intend to send the tournament or tournament ID.

Method 1:

$stateProvider
    .state('dashboard.tournament', {
        url: '/dashboard/tournament/:tournamentId'
        templateUrl: //...,
        controller: //...
    });

This defines a :tournamentId segment in the URI, waiting for the stateParams value upon state transition. The URL may display as something like /dashboard/tournament/7 when using

$state.go('dashboard.tournament', {id: 7});
.

Method 2:

$stateProvider
    .state('dashboard.tournament', {
        url: '/dashboard/tournament'
        templateUrl: //...,
        controller: //...,
        params: {
            tournamentId: null
        }
    });

In this approach, :tournamentId is removed from the URL.

StateParams can still be set similarly with

$state.go('dashboard.tournament', {tournamentId: 7});
, but no changes will reflect in the URI.

Both methods allow accessing the tournamentId value in the second controller through $stateParams.tournamentId.

Choosing a Method:

The main distinction is that method 2 conceals the param value in the URL. This is beneficial for abstract states without any visible URIs. Otherwise, the methods are quite similar, achieving the same outcome differently.

For URLs like

http://domain.com/dashboard/tournament/7
, opt for method 1. For URLs like
http://domain.com/dashboard/tournament
, prefer method 2.

Consult the routing documentation for further insights.

Answer №2

To ensure seamless navigation to a specific tournament dashboard, consider passing the tournament id as a state parameter to the dashboard controller. This way, when you choose a tournament from the menu, you will automatically be directed to the corresponding tournament dashboard.

Include the parameter in your state URL using $stateProvider:

.state('app.dashboard', {
     url: '/dashboard/:tournamentId',

In your app.js (Menu Controller):

$state.go('dashboard.tournament',{'tournamentId': vm.selectedTournamentId});

Then, access this parameter in your DashboardController by utilizing $stateParams (don't forget to inject $stateParams into your controller):

var tournamentId = $stateParams.tournamentId;

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

Unable to fetch source for HTML img tag

I am struggling with using jQuery to retrieve the src attribute of an image when it is clicked. Unfortunately, my current code does not output anything to the console and returns undefined when I try to manipulate it in the browser console. I do not have m ...

What is the reason behind plugins frequently neglecting to properly privatize their functions?

Many plugins utilize an underscore to indicate a function is private while still allowing public access. But why? We have options like .call, .apply, or .bind for managing the "this" keyword, or we can use the "self" pattern which is reportedly 60% faster ...

How are Node and projects utilizing Node modules related to each other?

Having experience with React and React Native in several projects, I am now shifting my focus to learning Node JS. Throughout my previous work, I have relied on npm for downloading node modules and executing commands like npm start. However, I have a few q ...

What is the best way to effectively apply chunking and batching when working with a group of promises or async functions?

When processing a large collection of async functions in batches, I am presented with two different scenarios: Scenario 1: Gathering all the async functions import { chunk } from "lodash"; const func = async () => new Promise((resolve) =& ...

What causes queryAsync() to generate additional metadata?

Following the instructions provided in a response to a question, I utilized queryAsync() and it is functional. However, it is appending excessive meta data to my query result, which was initially a simple query. This is the code snippet I am using to exec ...

Unable to update due to outdated response call causing issues

I am currently in the process of updating outdated response calls and have encountered a peculiar issue where the response is not being properly ended. Typically, I would use : res.send(200, {message: 'Location Updated'}); However, this method ...

What is the best way to transmit several data fields to a PHP page using Ajax?

Having an issue where I need to send 2 posts to my author PHP page using AJAX. Here's my original code: $.ajax({ type: "POST", url: "includes/get_competitions.php", data:'sport=<?php echo $_GET['sports']; ?>', success: func ...

Issues with Angular Material Pagination functionality may be causing unexpected behavior

I'm facing an issue with displaying data in an HTML table using an API. I've tried to implement pagination to show 3 or 6 rows per page, but it's not working as expected. Currently, all the data is being displayed without any pagination, whe ...

Slider Jquery - Displaying Half-Step Visual Bar Lengths

JSFIDDLE $(function() { $( "#slider-range-min" ).slider({ range: "min", value: 5, min: 0, step: .5, max: 10, slide: function( event, ui ) { $( "#amount" ).val(ui.value); ...

Detecting when the "enter" key is pressed using Jquery instead of relying on a mouse click

One issue I am facing is that jQuery is detecting the "enter" key press instead of mouse clicking on the submit button when trying to submit a form. The submit button works fine on the first attempt, but after that it only responds to the "enter" key. He ...

Dynamic resizing of grids using React and TypeScript

I'm attempting to create a dynamic grid resizing functionality in React and TypeScript by adjusting the lgEditorSize value on onClick action. Setting the initial lgEditorSize value const size: any = {}; size.lgEditorSize = 6; Adjusting the lgEditorS ...

Guide on dynamically updating data from a database in Chart.js without encountering data retrieval issues

I am completely new to using chartjs in my laravel project. Currently, I am struggling to create a chart that updates automatically without refreshing the page, pulling data from a MySQL database. I came across this code online: https://codepen.io/jordanwi ...

Issue with ng-selected not functioning properly

I am facing an issue where the ng-selected is assigned as true but the option is not being selected. The following is my controller code: .controller("PendingInvoiceCtrl", function($scope, $location, safeApply, dataService) { var userData = dataServi ...

What is the best method for interpreting XML using JavaScript?

I am facing a challenge with fetching and parsing an XML file using JavaScript. The XML-file is beyond my control. Recently, there has been a change in the encoding of some XML files which prevents the code from being parsed successfully. Previously it wa ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

What is the best way to delay a recursive JavaScript function for 3 seconds?

Before writing this post, I have already come across the following questions: how-to-pause-a-settimeout-call how-to-pause-a-settimeout-function how-to-pause-a-function-in-javascript delay-running-a-function-for-3-seconds Question The below code snipp ...

Incorporate payment processing functionality into your IONIC app by connecting a

Do not flag this question as a duplicate or already answered. If you have knowledge on this subject, please provide an answer. I am attempting to incorporate the payumoney payment gateway into my hybrid app. After following several tutorials, I have resor ...

Please enter a numerical value into the input field in a JavaScript form

<script> function loop() { var input = document.getElementById('inputId').value; for (var i = 0; i < input; i++) { var result = document.getElementById('outputDiv').innerHTML ...

"Encountering an issue with Express.json where it fails to parse the

Receiving JSON POST data from an IoT API that includes multipart form-data. Occasionally, an image file may be included but I only want to focus on the JSON part: POST { host: '192.168.78.243:3000', accept: '*/*', 'content-le ...

jQuery script located on local server fails to function

After downloading the jQuery.js file from jQuery.com, I made sure to save it in multiple locations - including JRE/Lib and my desktop where the HTML file that calls it is located. The script reference looks like this: <head> <script type= ...