value passed via Service is not being updated in the second controller

1

I tried to share a scope between two controllers , and I saw that one option would be the service or a factory > that use the singleton pattern, but I have already tried both and what happens is that I can not set the value of a controller to another, in the example below I wanted it to print example.com. br but is printing test .

First controller

app.controller('ctrRelatorioBolsaPorOrientador', ['$scope','$http', '$filter', '$routeParams', 'PropriedadesCompartilhadas',function($scope, $http, $filter, $routeParams, PropriedadesCompartilhadas) {

            $scope.url_grafico  =  'exemplo.com.br';
            PropriedadesCompartilhadas.set($scope.url_grafico);
}

Second controller

app.controller('ctrRelatorioBolsaPorOrientadorPdf', ['$scope','$http', '$filter', '$routeParams', 'PropriedadesCompartilhadas',function($scope, $http, $filter, $routeParams, PropriedadesCompartilhadas) {

      $scope.url_grafico = PropriedadesCompartilhadas.get();
}

app.js (factory)

var app = angular.module("sicite", ["ngRoute", "ngAnimate", "ngSanitize", "ui.bootstrap", "ngPasswordMeter", "angular-loading-bar", "googlechart"]);

app.factory('PropriedadesCompartilhadas', function() {
    var valor = 'teste';

    function set(data) {
        valor = data;
    }
    function get() {
        return valor;
    }

    return {
        set: set,
        get: get
    }

});

Result

    
asked by anonymous 03.04.2018 / 21:24

1 answer

1

This is because you are referencing a literal value.

A literal is its own instance: When you update the value of url_grafico you are associating a new literal value. Your second controller will not receive the updated value.

In the example below the value of url_grafico is stored as a property of an object. This object is then shared; the second control gets a reference to it.

angular
.module('myApp', [])
.factory('PropriedadesCompartilhadas', function() {
    this.dados = {};
    return this;
})
.controller('ctrRelatorioBolsaPorOrientador', function($scope, PropriedadesCompartilhadas) {
  $scope.setarValor = function(){
    PropriedadesCompartilhadas.dados.url_grafico = 'exemplo.com.br';
  };
})
.controller('ctrRelatorioBolsaPorOrientadorPdf', function($scope,PropriedadesCompartilhadas) {
  $scope.dados = PropriedadesCompartilhadas.dados;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><divng-app="myApp">
  <div ng-controller='ctrRelatorioBolsaPorOrientador' style='border:1px solid red'>
  <button ng-click='setarValor()'>Setar Valor</button>
  </div><br/>
  <div ng-controller='ctrRelatorioBolsaPorOrientadorPdf' style='border:1px solid blue'>
  
  {{dados.url_grafico}}
  </div>
</div>
    
03.04.2018 / 21:46