How to pass an Object to another page using Angularjs?

Asked

Viewed 8,785 times

2

I would like to know about the manipulation of objects between pages using Angularjs, for example: I have a product page, I make a request and bring my data using the basics of Angularjs.

My problem is when I need to pass a selected object to another page, which methods to do this using Angularjs?

3 answers

3

Working with HTML5 there is the implemented feature window.sessionStorage which is intended to store information as long as the browser session exists, that is, until you close the browser. In this example you have Jquery and Angular to be referenced on pages.

Code Example

home html.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="js/jquery-1.11.0.min.js"></script>
        <script src="js/angular.min.js"></script>
        <script>
            var App = angular.module('App', []);
            App.controller('Controller', function($scope, $http){
               $scope.peoples = [
                 {id: 1, name: 'People 1'},  
                 {id: 2, name: 'People 2'},
                 {id: 3, name: 'People 3'}                 
               ]; 
               $scope.edit = function(id){                   
                   var i = 0;
                   var a = false;
                   while (i < $scope.peoples.length && a === false){
                       if ($scope.peoples[i].id === id){
                           a = true;
                       } else {
                           i++;
                       }
                   }
                   if (i < $scope.peoples.length){
                        window.sessionStorage.setItem('people', JSON.stringify($scope.peoples[i]));
                        window.location.href='edit.html'
                   } else {
                       alert('Item não encontrado');
                   }
               }
            });
        </script>
    </head>
    <body>
        <div ng-app="App">
            <ul ng-controller="Controller">
                <li ng-repeat="people in peoples">
                    <a href ng-click="edit(people.id)">{{people.name}}</a>
                </li>
            </ul>
        </div>
    </body>
</html>

Edit.html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="js/jquery-1.11.0.min.js"></script>
        <script src="js/angular.min.js"></script>
        <script>
            var App = angular.module('App', []);
            App.controller('Controller', function($scope, $http){
               $scope.people = {};
               $scope.init = function(){                   
                   $scope.people = JSON.parse(window.sessionStorage.getItem('people'));
                   window.sessionStorage.removeItem('people');
               }
               $scope.init();
            });           
        </script>
    </head>
    <body>
        <div ng-app="App" ng-controller="Controller">            
            <label for="id">Id:</label>
            <input type="text" ng-model="people.id" id="id">
            <br>
            <label for="id">Nome:</label>
            <input type="text" ng-model="people.name"id="name">
        </div>
    </body>
</html>

This way, the information contained in home.html is passed to Edit.html.

Obs: this code can be improved through your web application, that is, open home.html and click on some item being redirected to Edit.html and the clicked item will appear on that other page. I did not make a point of putting a code criticized but, yes functional and with this should be adapted as already said its application.

1

By "another page," you refer to another external site or other view within the Single-Page Application itself served by Angularjs?

If you go inside Angular, you can create a service to request information from a backend and keep the status on it. For this, there are two ways: using service or using Factory.

Once you’ve done the service, you’ll just have to inject it into your controller that will need the information you’re referring to.

I wrote here an example. I hope it helps you understand more about Angular.

In the example, we have the home page that takes you to the user list. From there, you can see the profile of a certain user. The user list view and the profile view have different controllers, but they share the same service, which I called Usuariosmodel. Then data persists between views if you use a service. :)

Note that I have put everything (the codes and templates) inline so I can run everything at once in JSBIN and here in Stack Overflow. In practice, you would have to separate everything into different files to better structure your web application.

<!DOCTYPE html>
<html ng-app="exemploApp">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      .painel-de-usuario {
        background-color: AntiqueWhite;
        border: 2px solid black;
        border-radius: 12px;
        padding: 12px;
        margin-bottom: 6px;
      }
      .perfil-de-usuario {
        background-color: #ecc7c7;
        padding: 16px;
        border: 3px solid blue;
        border-radius: 9px;
      }
    </style>
  </head>
  <body>
    <div ui-view></div>

    <!-- AngularJS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
    <!-- Angular UI Router -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"></script>

    <script type="text/ng-template" id="usuarios.tmpl.html">
      <h1>Lista de usuários</h1>
      <div class="painel-de-usuario" ng-repeat="usuario in ctrl.usuarios">
        <p>
          Id: {{usuario.id}}
        </p>
        <p>
          Nome: {{usuario.nome}}
        </p>
        <p>
          Idade: {{usuario.idade}}
        </p>
        <a href="#/usuarios/{{usuario.id}}">Ver perfil</a>
      </div>

      <h4>Debug:</h4>
      {{ctrl}}
    </script>

    <script type="text/ng-template" id="perfil.tmpl.html">
      <h1>Ver Perfil</h1>
      <p>
        Esse é o perfil do usuário com identificação {{ctrl.perfil.id}}
      </p>

      <div class="perfil-de-usuario">
        <p>
          <strong>Nome:</strong> {{ctrl.perfil.nome}}
        </p>
        <p>
          <strong>Idade:</strong> {{ctrl.perfil.idade}}
        </p>
      </div>

      <a ui-sref="usuarios">Voltar pra lista de usuarios</a>

      <h4>Debug:</h4>
      {{ctrl}}
    </script>

    <script>
      angular.module('exemploApp', ['ui.router'])
        .config(function($stateProvider, $urlRouterProvider) {
          // Pra onde ir se nenhuma rota definida foi pedida
          $urlRouterProvider.otherwise("/home");

          // Defina todos os states aqui (aka routes (rotas))
          $stateProvider
            .state('home', {
              url: "/home",
              template: `
                <h1>Bem vindos!</h1>
                <a ui-sref="usuarios">Usuarios</a>
              `
            })
            .state('usuarios', {
              url: "/usuarios",
              templateUrl: "usuarios.tmpl.html",
              controller: "UsuariosCtrl",
              controllerAs: "ctrl",
            })
            .state('perfil', {
              url: "/usuarios/:id",
              templateUrl: "perfil.tmpl.html",
              controller: "PerfilCtrl",
              controllerAs: "ctrl",
            })
          ;
        })

        .controller('UsuariosCtrl', ['UsuariosModel', function(UsuariosModel) {
          var ctrl = this;

          function getUsers() {
            // Para carregar os usuarios usando o service
            UsuariosModel.all()
              .then(function(response) {
                ctrl.usuarios = response;

              })
              .catch(function(error) {
                console.log("Erro carregando usuarios");
                console.log(error);
              });
          }

          // Carrega todos os usuarios
          getUsers();
        }])

        .controller('PerfilCtrl', ['UsuariosModel', '$stateParams', function(UsuariosModel, $stateParams) {
          var ctrl = this;

          // Para carregar o perfil de um usuario especifico
          function getUser(userId) {
            UsuariosModel.get(userId)
              .then(function(response) {
                ctrl.perfil = response;
              })
              .catch(function(error) {
                console.log("Problema ao carregar perfil do usuario " + userId);
                console.log(error);
              });
          }

          // Carrega perfil do usuario
          getUser($stateParams.id);
        }])

        .service('UsuariosModel', ['$http', '$q', function($http, $q) {
          var service = this;

          // Dados fake so de exemplo
          // Normalmente, os dados estariam em um banco de dados no backend
          var DATA = [
            { id: 1, nome: "Pedro", idade: 22 },
            { id: 2, nome: "James", idade: 32 },
            { id: 3, nome: "Ana", idade: 19 },
            { id: 4, nome: "Timothy", idade: 45 },
            { id: 5, nome: "Yumiko", idade: 28 },
            { id: 6, nome: "Xiaoyu", idade: 33 },
          ];

          service.all = function() {
            // NOTA: estou usando $q pra retornar uma promessa com os dados
            // que estao na variavel DATA; isso não é necessário se você tiver
            // um backend, em qual caso você só iria precisar do $http
            // (então remova $q das dependências se estiver usando $http)
            var deferred = $q.defer();

            deferred.resolve(DATA);

            return deferred.promise;

            // Normalmente, você usaria isso se tivesse um backend
            // return $http.get(URL_DO_SEU_BACKEND + "usuarios/").then(extract);

            // Onde extract é definido (no começo do service) como
            // function extract(result) {
            //   return result.data;
            // }
          };

          service.get = function(userId) {
            var deferred = $q.defer();

            deferred.resolve(DATA[userId - 1]);

            return deferred.promise;

            // Normalmente, você usaria isso se tivesse um backend
            // return $http.get(URL_DO_SEU_BACKEND + "usuarios/" + userId).then(extract);

            // Onde extract é definido (no começo do service) como
            // function extract(result) {
            //   return result.data;
            // }
          };

        }])
      ;

    </script>


  </body>
</html>

1

Perfectly what you were looking for, let’s imagine, I searched the data, displays it on a page, when it was the moment of editing if I passed the ID of this object by the url, and in this new page captures this ID to fetch the data and so displayedFor the editing, it would be unworkable correct? because I made two requests, one to display all the data and the other to display only a certain one. Your solution was very interesting, thank you!

  • If you have solved the problem mark as answer :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.