How can I transfer a value from one form to another using AngularJS?

Trying to retrieve the Id from a table and pass it to a controller, however, I am facing an issue where the Id value is lost every time the form changes. Is there a better way to handle this? Below is the service and controller code:

//Retrieving IdValue

app.controller('SeguimientoSolicitudesController', ['$scope', 'ParametrosSolicitudes', function ($scope, ParametrosSolicitudes) {
        this.SegSolic = "";        
        var self = this;

        $scope.ValorId = function (value) {
            ParametrosSolicitudes.setVarIdSolicitud(value);
            window.location.href = urlServer + "Home/About";
        };


        solicitudContext.obtenerListaSegSolicitudes(function (resp) {
            switch (resp.ressult) {
                case "tgp":
                    self.SegSolic = solicitudContext.ListaSeguimientoSolicitudes;
                    break;
                case "notgp":
                    break;
                default:
                    break;
            }
            $scope.$apply();
        });       
    }]);

//Getting detail of the selected id but value is missing
app.controller('SolicitudesController', ['$scope', 'ParametrosSolicitudes', 'parameterConstant', function ($scope, ParametrosSolicitudes, parameterConstant) {
        this.SolicitudDetalle = "";
        var IdSolicitud = '';
        var self = this;

        $scope.$watch(function () { return ParametrosSolicitudes.getVarIdSolicitud() }, function () {
            IdSolicitud = ParametrosService.getVarIdSolicitud();
        });
        solicitudContext.obtenerListaSolicitudes('R', IdSolicitud, function (resp) {
            switch (resp.ressult) {
                case "tgp":
                    self.SolicitudDetalle = solicitudContext.ListaSolicitudes;
                    break;
                case "notgp":
                    break;
                default:
                    break;
            }
            $scope.$apply();
        });
    }]);

Answer №1

Rafa, it seems like you have encountered a conceptual issue. When you reload the page in JavaScript, any variables stored will be lost. This means that when you use:

window.location.href = urlServer + "Home/About"

You end up losing all data on the client side.

Instead of using the method above, for navigating from one page to another in AngularJS, it is recommended to utilize the $location service. In your case, you can achieve this by using something like: $location.path("Home/About");

https://docs.angularjs.org/api/ng/service/$location

Please refer to this sample code below:

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when('/', {
controller: "SeguimientoSolicitudesController",
templateUrl: "SeguimientoSolicitudes.html"
})
    .when('/details/:id/', {
controller: 'SolicitudesController', 
templateUrl: "Solicitudes.html"
})
}]);

app.service("shareService", function(){
// Note that this value will be lost upon reloading the page. If you need it to persist, consider saving it to the server or browser (cookies, localStorage).
var name = null;

return {
getName: function(){
return name;
},
setName: function(val){
name = val;
}
}
})

app.controller('SeguimientoSolicitudesController', ['$scope', '$location','shareService',function ($scope, $location, shareService) {       
$scope.list = [{id: 5, name: "NameA"}, {id: 9, name: "NameB"}];

$scope.goToDetails = function(item){
shareService.setName(item.name);
$location.path("details/" + item.id);
}
}]);    
    
app.controller('SolicitudesController', ['$scope','$routeParams','shareService',function ($scope, $routeParams, shareService) {                    
$scope.id = $routeParams.id;
$scope.name = shareService.getName();
}]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container"  ng-app="app">
<ng-view></ng-view>

  <script type="text/ng-template" id="SeguimientoSolicitudes.html">
    <p ng-repeat="item in list">
      <a class="btn btn-link" ng-click="goToDetails(item)" style="cursor: pointer;">{{item.name}}</a>
    </p>
  </script>

  <script type="text/ng-template" id="Solicitudes.html">
     <p>ID: {{id}}, NAME: {{name}}</p>
      <a class="btn btn-link" href="#/">back</a>
  </script>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.min.js"></script>

I hope this information proves to be helpful 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

Every div must have at least one checkbox checked

Coding in HTML <div class="response"> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> </div> <div class="response"> <input type="check ...

What is the best way to access the attribute of an AJAX response?

resp.getWriter().write("msg=1?id=" + l1); Within the code snippet below, I am able to retrieve the responseText. However, I am wondering how can I extract an attribute from the response text. Sample AJAX Code: function updatecategories(cu) { var r1 = ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Update the CSS dynamically using JavaScript or AngularJS

Is there a way to dynamically modify this CSS style using JavaScript or in an Angular framework? .ui-grid-row.ui-grid-row-selected > [ui-grid-row] > .ui-grid-cell{ background-color: transparent; color: #0a0; } .ui-grid-cell-focus ...

Can GET or POST variables be transmitted to external JavaScript?

Is it possible to pass a variable to an external JavaScript file? For instance: Suppose I have the following code: <script type="text/javascript" src="gallery.js"></script> I'm curious to know if it's feasible to pass an argument ...

Tips for integrating the C++ icon into a ReactJs project

For a ReactJs project, I needed to include icons of different Languages and Tools. When adding a Python icon, I used: <ListItem> <ListItemIcon className={classes.icon}> <span className="iconify" data-icon= ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Issue with ng-repeat causing HTML table data to not appear

Trying to create a Flask web app, I encountered an issue while attempting to display tabular data on my webpage using AngularJS. Despite using ng-repeat to iterate through the data, it doesn't seem to work and no errors appear in the console. Can anyo ...

Connecting a JavaScript script from my HTML file to Django's static files - here's how

I recently started a Django project with frontend code that wasn't initially written for Django. I am having trouble connecting this script: <script> document.body.appendChild(document.createElement('script')). src='js/ma ...

Authentication Error (401) in WordPress JWT

Recently, I came across WordPress and started using it. However, I encountered some issues while trying to integrate JWT with a custom endpoint. Despite configuring my API and JWT correctly, I faced an authentication problem during my AJAX request. It&ap ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...

Enhance your ng-boilerplate by incorporating angular ui bootstrap 3

Recently, I integrated Bootstrap 3 into my AngularJS v1.2.0-rc.3 project that is based on ng-boilerplate. However, I encountered an issue where grunt fails during the karma tests execution. After some investigation, I discovered that the problem lies in ...

Encountering an Error while Setting Up NextJS on Vercel

Hello, I'm a newcomer to the world of web development. My current goal is to deploy my first NextJS app on Vercel, but I keep encountering an error. Error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) ...

Steps to dynamically display a new view template when a button is clicked using ng-view

I am facing an issue with loading a new view upon clicking a button on my Index page. Each button has a click event associated with it and I need to load a corresponding view when the button is clicked. My index.html file contains a ng-view section where ...

Using JavaScript, display JSON data retrieved from a PHP file

Currently, I am in the process of developing a web application that displays tweets based on a city inputted by the user through an HTML form. The city value is stored in the $_SESSION['city'] variable after the form is submitted. Subsequently, ...

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

When HTML elements are dynamically inserted through JavaScript using quilljs, they may cause conflicts with the layout properties

I am currently working on creating a simple webpage layout similar to that of Stack Overflow, with a sidebar and a main content area that can scroll. In my case, the content area is intended to host a QuillJS text editor. To integrate the QuillJS editor i ...