Share object between two controllers in Angularjs

Asked

Viewed 1,094 times

1

I’m studying AngularJS and I’m trying to make a CRUD simple, however I am not able to have the same object of my listing for my form, that is, at the time you click the edit button go to the form filled by the object.

I have the Factory (I read about sharing data but only attribute, wanted to share the whole object)

app.factory('item', function(){
  return item; 
});

My list:

 <tbody>
   <tr ng-repeat="item in lista">
      <td>{{item.id}}</td>
      <td>{{item.descricao}}</td>
      <td>{{item.status}}</td>
      <td>{{item.prioridade}}</td>
      <td>{{item.tipo}}</td>
      <td>
         <a class="btn" href="#" ng-click="editItem(item)"><span class="glyphicon glyphicon-pencil"></span></a>
         <a class="btn" href="#" ng-click="deleteItem(item)"><span class="glyphicon glyphicon-trash"></span></a>
      </td>
   </tr>
</tbody>

And my Controllers

app.controller("listCtrl", function($scope, $http, $location, item){
    $scope.itemAux = item;
    $scope.loadData = function(){ ... };
    $scope.deleteItem = function(item){ ... };

    $scope.editItem = function(itemX){
         $scope.itemAux = itemX;
         $location.path('/cadastro');
    };
}

app.controller("formCtrl", function($scope, $http, $location, item){
    $scope.itemAux = item;

    $scope.save = function(){ ... }
    $scope.update = function(){ ... }
}
  • http://stackoverflow.com/questions/12008908/angularjs-how-can-i-pass-variables-between-controllers

1 answer

1


There are some ways to get the result you want, how to use $rootScope, $broadcast or store the data in SessionStorage or LocalStorage, etc..

One of the simplest ways is to create a Service to share the data between the two Controllers, Example:

angular.module('myApp',[]);

angular.module('myApp').factory('myService', function() {
 var valor = {}
 
 function set(data) {
   valor = data;
 }
 function get() {
  return valor;
 }

 return {
  set: set,
  get: get
 }

});
angular.module("myApp")
    .controller("ctrl1", function($scope, myService){
    $scope.pessoa = {id: 1, nome: 'Diego', idade: 23};
    //Atribui um valor ao serviço
    myService.set($scope.pessoa);
});
angular.module("myApp")
    .controller("ctrl2", function($scope, myService){
     //Pega o valor atribuido ao serviço
     $scope.pessoa = myService.get();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="ctrl1">
     <h1>Controller 1</h1>
  Atributo: {{pessoa.nome}}!
</div>

<div ng-controller="ctrl2">
  <h1>Controller 2</h1>
  Objeto: {{pessoa}}!
  <br>
  Atributos: {{pessoa.nome}} -- {{pessoa.idade}}!
</div>
</div>

For more information I recommend the links:

Services

Factory x Services

  • Thanks, did not know about service, gave straight. thanks!

Browser other questions tagged

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