Angular share Information

1

Good morning, I have the following code

Angular

 var aplicacion = angular.module('app',[])
aplicacion.factory('datosCompartidos', function (){
  var datosCompartidos = {}
  datosCompartidos.contador = 0
  datosCompartidos.getContador = function(){
    return datosCompartidos.contador
  }
  setInterval(function check(){
        datosCompartidos.contador +=1
    console.log(datosCompartidos.contador)
    }, 1000);//cada 1 minuto
  return datosCompartidos
})

aplicacion.controller('profile',['$scope','datosCompartidos',function($scope,datosCompartidos){
  $scope.m = datosCompartidos.contador
}])

HTML

<div ng-app="app">
   <div ng-controller="profile">
    {{m}}

  </div>
 </div>

My problem is that the value of m in the $ scope is not updated, as I should do, I should add some $ watcher

    
asked by Matias 28.10.2017 в 16:50
source

2 answers

0

what you would have to do to update in other controllers is to use the $ rootScope with the $ on something like that ..

  • this you put in the controllers that you want the variable to be updated
  

$ rootScope. $ on ('table_variable', function (event, obj) {
  $ scope.m = obj.variable; });

  • and with this you execute it from any controller and send the parameter to update
  

$ rootScope. $ broadcast ('update_variable', {variable: 'new value'});

    
answered by 30.10.2017 / 20:19
source
0

There are some things you must fix. First, you have an interval that you want to run every 1 minute, however you are spending 1 second. The time, both in setInterval and in setTimeout is given in milliseconds, so it would be 60000. The other thing is that if m is not updated alone, you should try placing the counter inside the controller, after all , there is not much code and if it still does not update, you can call the function $scope.$apply( function() { $scope.m = ...; } ) and that if you update it immediately.

    
answered by 29.10.2017 в 03:20