How can data be passed between controllers without utilizing URLs?

I am working on a web application with two pages using AngularJS. Here is the JSON file I am using:

{
    "data": [

        { "name": "bhav",
"id": 123
            },
{"name": "bhavi",
"id": 1234
},
{"name": "bhavk",
"id": 1235
}
]
}

Here's my app.js (Routing file):

myApp = angular.module('myApp', ['slickCarousel',
  'ngRoute',
  'myAppControllers',
    'myAppServices','swipeLi'
]);

myApp.config(['$routeProvider',
  function($routeProvider) {

    $routeProvider.
      when('/', {
        templateUrl: 'partials/home-page.html',
        controller: 'ProfileListCtrl',
    }).
    when('/profile/:typeofprofile', {
        templateUrl: 'partials/profile-detail.html',
        controller: 'ProfileDetailCtrl'
      })
}]);

The structure of my first page (home-page.html) is as follows:

<div ng-repeat="data in data">
<a href="profile/myfriend">{{data.name}}</a>
</div>

On the second page (profile-details.html), I need to retrieve the id number of that profile without passing it through the URL since I am fetching data from the JSON file using an http.get request in the controllers.

Please provide assistance on how to fetch the id or name of the clicked profile without passing it through the URL.

Note: I have already reviewed resources like this one: Angular ui router passing data between states without URL, but it did not address my specific issue.

Answer №1

As mentioned in the comments, the method you can use to pass data is $state.go(). Passing parameters with $state.go() is quite straightforward. You just need to include ui.router in your application. I have set up two partial views to demonstrate passing parameters from header.html to side.html.

Your JavaScript code will look something like this:

var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("/");
  $stateProvider.state('top', {
      url: "",
      templateUrl: "header.html",
      controller: 'topCtrl'
    })
    .state('top.side', {
      url: '/app/:obj/:name',
      templateUrl: "side.html",
      controller: 'filterCtrl'
    })
});

app.controller('topCtrl', function($scope,$state) {
          $scope.goItem = function(){
            $state.go('top.side',{obj:441,name:'alex'});
          };
      });


app.controller('filterCtrl', function($scope,$state) {
  console.log(JSON.stringify($state.params));
  $scope.params = $state.params;
      });

You can access a working example on PLUNKER where you can see how the views, controller, and script are structured:

http://plnkr.co/edit/M1QEYrmNcwTeFd6FtC4t?p=preview

I have explained methods for using both ui-sref and $state.go() to pass $stateParams. However, if you want to share data across all controllers, refer to my answer in this question:
Share Data in AngularJs

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

What is the method for selecting the element currently under the mouse cursor?

Is it possible to change the color of all elements you hover over using plain Javascript without jQuery? HTML <ul> <li></li> <li></li> <li></li> </ul> JavaScript (function() { var item = ...

Hey Node, what is the process for setting response headers in a node/express application?

I am currently working on a project with a basic server setup. One of the requirements is that I need to ensure the response header sent back is 200. I have included the current code for the server below, but I am unsure about how to properly send respon ...

Forwarding the geographic coordinates directly to the system's database

I have a unique script that retrieves the precise latitude and longitude position. It then automatically sends this data to a database without the need for user input. <script> function getPosition(position) { var latitude = position.coor ...

The $urlRouterProvider.otherwise function does not integrate smoothly with ui-router

I am currently using ui-router version 1.0.11 for AngularJs 1.x The issue I am facing: When a user enters an address like: /url/abcdef that is not in my route configuration, they should be automatically redirected to /products. This redirection works fin ...

What is the purpose of using href="javascript:void()?

As I was pondering over this query: What exactly does "javascript:void(0)" signify?, I realized the rationale behind using <a href="javascript:void(0)" - to prevent any redirection of the page. Recently, I stumbled upon this snippet of code: <a id= ...

Is it possible to use Angular JS nested ng-repeat with only one top-level object?

My JSON object contains package ordering data. I am able to list all orders, parcels within each order, and SKUs in each parcel using a nested loop structure like the one below. <div ng-repeat="order in orders"> order {{order.ordernum}} <div ...

The trouble with dynamicHelpers in Nodejs Express

Trying to make my app run smoothly, I've set up the following configurations: app.configure(function(){ app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine', 'j ...

Issue with AJAX POST method failing to upload the file

I'm having trouble incorporating file upload support into my AJAX post function. Can anyone provide some guidance on what I might be missing? function ajax_post(url, param) { if (url.substr(0, 11) == 'javascript:') { result = &ap ...

Trading keys between arrays in JavaScript

I have a set of simple objects contained within an array: var myObject1 = [ {name: "value1", adddress: "545454545445"}, {name: "value2", adddress: "323233223"}, {name: "value3", adddress: "332 ...

Minimize JavaScript code for simplifying jQuery CSS modifications (show/hide off-canvas navigation)

I am currently working on developing a custom off-canvas navigation system that is similar to the functionality of Foundation. Essentially, I have 2 icons that trigger CSS adjustments when clicked. I am contemplating whether it is feasible to streamline th ...

Counting JQuery Classes in an HTML Document

My task involves creating a dynamic HTML form that allows users to enter card values, which are then counted and styled accordingly. Each set of cards is contained within a <section> element. However, I encountered an issue with my jQuery code where ...

Exploring the application of conditional logic within HTML coding

I am working on ensuring that Part II of the HTML page only runs once all required information has been successfully submitted through the form. This particular issue is within a Flask application. I need to run Part II after Part I in order to prevent an ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

How can you load elements via AJAX?

Using AJAX, I successfully load content from a PHP page. Now, my challenge is to access and interact with the dynamically loaded elements (such as buttons, forms, or divs). The code snippet that is causing issues: jQuery(document).ready(function() { $( ...

A guide on updating data with duplicate values in Knex

Suppose I have the following array of data: const customerIds = [ '7d8206d2-74bc-4b90-a237-37f92486cde4', 'e594fe7f-d529-4a2f-ab24-ffc4e102268c', '7d8206d2-74bc-4b90-a237-37f92486cde4' ] As seen, there are duplicate IDs ...

The Mongoose .lt method is unable to process the post value

I came across this interesting Mongoose function snippet: exports.readSign = function(req, res) { if (req.user.roles.indexOf('admin') === 1) { Timesheet.find() .where('projectId').equals(req.params.projectId) ...

Implementing AWS EC2 security measures to restrict access to HTTP requests that are specifically initiated when a browser accesses static content stored in an S

In implementing a distributed deployment on AWS, all static web assets, such as AngularJS files and dependencies, have been shifted to an AWS S3 bucket (static website). The AngularJS controllers have the API URL pointing to a Node.js server running on an ...

When trying to use express, the error message "d3.scale is

Having trouble integrating a c3-chart into my web application using node.js and express. The c3.js file is throwing the error message: TypeError: d3.scale is undefined Here is an excerpt from my layout.yade file: doctype html html head title= titl ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

Transform the given string into an array by eliminating all instances of the plus symbol

I need help converting strings into an array by removing the "+" characters. Currently, it is only converting the first element and not all of them. Can you assist me in converting all instances of "+" to "," for every element? let myString = 'jan + f ...