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

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...

Update the content inside a <p> tag dynamically using Javascript based on the selected option

Struggling with Javascript and need some guidance. I have a select box with 4 options, and I want to update the contents of a <p> tag with an id of pricedesc based on the selected option. Here is my current code: function priceText(sel) { var l ...

Tips for transferring a JavaScript variable to a Java servlet using the doPost method

I am working with an HTML table that contains dropdowns. When a user clicks on a dropdown, I store the column name and corresponding row (billdate) in a variable. Now, my goal is to pass this variable to my Java servlet's doPost method and then use it ...

Is it possible to select a date from the datepicker, or should I move to the next month to find an

Protractor newbie here, attempting to test a date picker with Protractor. My attempt at selecting an available date: this.selectAvailableDate = element(by.css('td[aria-disabled="false"]')); If the desired date is not in the current month, I nee ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Tips on efficiently rebinding jQuery events to dynamically loaded content without having to manually do it for each event or class

Recently, I encountered an issue with my jQuery app where I needed to bind different functions to elements within one div dynamically. Specifically, I had a "delete-function" attached to all ".btn-delete" elements and an "add-function" linked to all ".btn- ...

How come the method $.when().pipe().then() is functioning properly while $.when().then().then() is not working as expected

I'm still grappling with the concept of using JQuery's Deferred objects, and am faced with a puzzling issue. In this code snippet, my attempt to chain deferred.then() was unsuccessful as all three functions executed simultaneously. It wasn't ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

Efficiently transferring a style property to a child component as a computed property in Vue.js

Currently, I am facing an issue that involves too much logic in my inline style, which I would like to move inside a computed property. While I understand that this is the correct approach, I am unsure of how to implement it. To provide a clearer understa ...

sending properties to dynamically loaded components

I'm struggling with transferring props between children and parent components using Vue Routes. Within my Layout component, I have a wrapper DIV structured like this: <template> <div class="container" v-bind:class="cssClass ...

Retrieving information from a database and storing it in an array

I have developed an angular application with a PHP script that extracts database data into JSON upon request. Here is the snippet of code I am using to retrieve the data into an array: $values = array(); $query = "SELECT * FROM photos ORDER BY id"; $res ...

"Exploring the best way to retrieve the angular filter value within a Node.js environment

Currently, I am facing an issue with accessing the value in Node.js using req.body when it is stored in ng-model. The ng-model includes an AngularJS filter, and I need to retrieve this filtered value from the input field in Node.js through req.body. Below ...

Collect form input data containing a binary image and showcase it in a view using webapi

I am currently working on a webapi project using MVC architecture. The project involves converting a jpg image to binary data, sending it to a SQL server, and then retrieving the form data along with the image back as a jpg for display on the view. Althoug ...

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...

Unanticipated Behavior in JavaScript (jQuery): Triggering a Function Instead of Submitting a Form

I'm confused about something. Here's my issue: I have a specific type of form declaration where jQuery processes the form data and sends an Ajax request. Inside the form, there are buttons - one for form submission (Ajax) and another for calling ...

res.render() Displaying Data in Frontend using Local Variables

I have a question regarding defining local variables in Express. When I use res.render(view, {variable: variable}), how can these variables be accessed on the frontend? Where are they stored? I attempted to access a variable with console.log(variable), but ...

Update array when checkbox is selected/deselected

Using angular-google-maps, I am creating a map with various types of markers. Below the map, there are checkboxes in a simple form: <div class="mapOptions"> <form action="" class="form-inline" style="text-align:center"> <label for=""& ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...