How to transfer identification from one AngularJS page to another

I need help figuring out how to retrieve an ID from the list.html page and use that same ID to display corresponding details on the list-detail.html page. I am new to using angularjs and struggling with getting the details based on the ID. Below is my code snippet: index.html

    <body ng-app="myAppnew">
        <h1>Friends</h1>
        <section ui-view></section>
      </body>

list.html

<ol>
  <ul ng-repeat="friend in friends">
   <a ui-sref="listDetail({Id: friend.id})">{{friend.name}}</a>
  </ul>
</ol>

list-detail.html

<h1>Friend Detail</h1>
{{id}}<br />
{{name}}<br />
{{imageLocation}}<br />

app.js

var myApp = angular.module('myAppnew', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
    .state('list', {
      url: '/',
      templateUrl: 'list.html',
      controller: 'mainCtrl'
    })
    .state('listDetail', {
      url: '/:Id',
      templateUrl: 'list-detail.html',
      controller: 'mainCtrl'
    });
});

myApp.controller('mainCtrl', function($scope, $stateParams,$http) {
  console.log(arguments);
    $http.get("http://www.fashto.in/rest/getmaincategories").then(function (response) 
                                                           {
         $scope.friends = response.data;
              });


  function findFriend(id){
    var targetFriend = null;
    $scope.friends.forEach(function(friend){
      console.log("Test",friend.id,id,friend.id === id)
      if (friend.id === id) targetFriend = friend;
    }); 
    return targetFriend;
  }


  function list($scope, $stateParams) {
    var friend = findFriend(parseInt($stateParams.Id));

    angular.extend($scope, friend);
  }

  if ($stateParams.Id) {
    list($scope, $stateParams,$http);
    console.log($scope);
  }
});

Any assistance would be greatly appreciated.

Answer №1

It seems that the issue lies in passing unnecessary dependencies through function parameters, violating the principle of Dependency Injection.

To resolve this, simply remove the parameter from list and avoid passing it when calling the function.

function list() {
    var friend = findFriend(parseInt($stateParams.Id));

    angular.extend($scope, friend);
}

if ($stateParams.Id) {
    list();
    console.log($scope);
}

NOTE: The following description highlights what was lacking in the current implementation for reference purposes only.

The main issue arose when calling the list function with three parameters like

list($scope, $stateParams,$http);
, whereas the function expected only two parameters defined as
function list($scope, $stateParams) {
. It is important to either add or remove a single parameter in one of the places.

Updated/Refactored Code

myApp.controller('mainCtrl', function($scope, $stateParams, $http) {
  //creating promise here
  var friendsPromise = $http.get("http://www.fashto.in/rest/getmaincategories").then(function(response) {
    $scope.friends = response.data;
});


function findFriend(id) {
  var targetFriend = null;
  //wait till promise resolve
  friendsPromise.then(function() {
    $scope.friends.forEach(function(friend) {
      if (friend.id === id)
        scope.friend = friend; //set current friend.
    });
});
}

function list() {
  findFriend(parseInt($stateParams.Id));
}

if ($stateParams.Id) {
  list();
  console.log($scope);
}
});

Then on view do {{friend}}/{{friend.id}}

Answer №2

var myApp = angular.module('myNewApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
    .state('list', {
      url: '/',
      templateUrl: 'list.html',
      controller: 'mainCtrl'
    })
    .state('listDetail', {
      url: '/:Id',
      templateUrl: 'list-detail.html',
      controller: 'mainCtrl'
    });
});

$scope.viewFriendDetails = function(friend) {
      $state.go('listDetail', {
        Id: friend.id
      });
    };

$scope.getDetails=function() {
$scope.friends.forEach(function(friend){  
      if (friend.id === parseInt($stateParams.Id)) {
        $scope.value=friend;
      } ;
    }); 
}
list.html

<ul>
  <li ng-repeat="friend in friends" ng-click="viewFriendDetails(friend)">
                {{friend.name}}
  </li>
</ul>

list-detail.html

ng-init="getDetails()"

<ul>
  <li>{{value.name}}</li>
  <li>{{value.id}}</li>
</ul>

Ensure to execute the getDetails function when the list-detail.html page is loading. Hopefully, this solution meets your requirements.

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

Similar to AngularJS Component's "require" property, Angular Component also has an equivalent

In the process of updating a sizable Angular 1.6 App, we encounter numerous components that utilize 'require' to access the parent component's controller. The structure of an AngularJS component appears as follows: var tileTextbox = { ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

Right-align SELECT-OPTIONS text

Here are the screenshots of the form I'm currently working on. I am aiming to create a select box in the form where the text within the options is aligned to the right. After an option is selected, the chosen text should be displayed as illustrated i ...

Fade the current Div out and fade in the following Div while also animating its child element

Looking to achieve a fade in and out effect for 3 divs, with the child element animating its way up from the bottom right once the divs have faded in. I've been working on it but haven't made much progress, does anyone have any ideas? Check out ...

Combine two sets of JavaScript objects based on their positions using Underscore.js

Data Set 1: {id: "01", name: "John Doe", age: "25", city: "New York", country: "USA"} Data Set 2: [{key:'id', value:'01'},{key:'name', value:'John Doe'},{key:'age', value:'25'},{key:'city& ...

Opening a fresh window with HTML content extracted from the existing page

Is there a way to open a new window and transfer some of the HTML content from the original page to the new window? For example: $("div#foo").click( function(){ var copyHTML = $("table.bar").html(); window.open(''); // how can we ...

Angular animation triggered when a specific condition is satisfied

I am working on an animation within my Angular application @Component({ selector: 'app-portfolio', templateUrl: 'portfolio.page.html', styleUrls: ['portfolio.page.scss'], animations: [ trigger('slideInOut&apo ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

How to select specific folders for packaging with asar within an Electron app

I'm currently working on an Electron application and experimenting with using asar to package the node_modules and sources directories, while excluding other directories. However, I've run into an issue where when building the application with a ...

Eliminate repeated entries in a drop-down menu and display them with commas in between

I am working with a list that contains various language combinations: German to English German to Spanish German to Chinese German to French English to Spanish English to French English to Greek English to Portuguese Does anyone have suggestions on how ...

What are some ways to enhance Redux's performance when handling rapid updates in the user interface?

I have been facing a challenge with integrating a D3 force graph with my redux state. During each 'tick' update, an action is dispatched to update a collection of positions in the redux state. These positions are then combined with node data to u ...

Is there a way to retrieve two distinct data types from a single ng-model within a select option?

My mean stack code is functioning well, but I am looking to enhance it by adding a new feature. Specifically, I want to retrieve more elements from my NoSql database while selecting options. This is the structure of my database: Tir2 :id, price, xin, yin ...

How can we verify that console.log has been called with a specific subset of expected values using Jest?

I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions: //utils.js export const util_sum = ( ...

Discovering a specific JSON object member by its corresponding string value

Let's consider a JSON file with information about books stored in it: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "autho ...

What is the best way to test the Express router catch branch in this specific scenario with Jest?

My current task involves working with a file containing two routes. The first route is located in routes/index.js const express = require('express') const router = express.Router() router.get('', (req, res, next) => { try { r ...

The window fails to load properly after building, but functions perfectly while in development server mode

My application is not displaying a window after it's built, but it works perfectly fine when I execute npm run serve Even though there is a process running in the task manager, the same issue persists if I try using the installer. I'm not receiv ...

My JavaScript code is functioning properly in jsfiddle, but when I try to run it on my own website, I encounter

Encountered an error message stating "Uncaught typeError: cannot call method 'hover' of null" following the line $('#nav li a').hover(function(){ in my JavaScript code. Check out the code on my site here: http://pastebin.com/GjZBEu3s Y ...

npm global packages: Accessing reference material from package files

I'm currently working on developing an npm package that will be globally installed. Can I include non-code files alongside code files that can be accessed in the code files? For instance, if my package contains someTextFile.txt and a module.js file ( ...

What is the reason that jQuery does not work on HTML generated by JavaScript?

One of my JavaScript functions, named getImages, is responsible for loading the following HTML structure: // Function starts here function getImages() { $.getJSON(GETIMAGELIST, function(data) { var items = []; // Populating the HTML $.each(dat ...

What is the best way to extract keys from a hash in Ruby using a Javascript string?

I am currently developing a command line tool using Ruby that is designed to parse JSON data from diverse sources and perform certain operations on the retrieved information. To make it user-friendly, I have incorporated a feature where users can configure ...