Share object between two controllers in angularjs

1

I am studying AngularJS and I am trying to make a CRUD simple, but I am not able to have the same object of my listing for my form, that is, when I click the edit button go to the completed form by the object.

I have Factory (I read about sharing data but only attribute, I wanted to share the entire 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(){ ... }
}
    
asked by anonymous 11.07.2016 / 18:32

1 answer

1

There are a few ways to get the result you want, such as $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><divng-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

    
11.07.2016 / 18:51