How to pass an Object to another page using AngularJS?

2

I would like to know about manipulating objects between pages using AngularJS, for example: I have a product page, in it I make a requisition and I bring my data using the basic of AngularJS.

My problem is when I need to pass a selected object to another page, what are the methods to do this using AngularJS?

    
asked by anonymous 30.08.2014 / 03:26

3 answers

3

Working with HTML5 is the window.sessionStorage implemented feature that is intended for information while the browser session exists, that is, until you close the browser. In this example you have JQuery and Angular to be referenced on the pages.

Code Sample

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>

In this way, the information contained in home.html is passed to edit.html.

Obs: This code can be improved through your web application, ie, 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 criticized but functional code and with that it should be adapted as I said its application.

    
30.08.2014 / 15:57
1

Perfectly what I was looking for, let's imagine, I searched the data, displayed it on a page, when it was time to edit if I pass the ID of that object through the url, and on that new page it is captured that ID for search the data and thus display them for editing would be unfeasible 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!

    
30.08.2014 / 22:33
1

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

If within the Angular, you can create a service to require information from a backend and maintain the state in it. For this, there are two ways: using service or using factory.

After doing the service, you will just have to inject it into your controller that will need the information you are referring to.

I wrote here for an example. Hope it helps you understand the Angular more.

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

Note that I have put everything (the inline codes and templates) in order to be able to 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><!--AngularUIRouter--><scriptsrc="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>
    
10.07.2016 / 07:56