AngularJS - share variable between two controllers

angularjs

Solution

`time` appears to be a primitive, which means it is returned byVal rather than byRef. In other words, each call to `getTime` will return the value that `time` is currently set to, and calls to `setTime` will change the value for future calls, but not for anything that already called it. This is a classic case of the angular rule, Always use a dot.

Try changing `time` to an object instead:

.factory('Timeline', function() {
  var timelines = [];
  var time = {
    value: null
  };
  return {

    getTime: function() {
      return time;
    },

    setTime: function(_time) {
      time.value = _time;
    }

  }
});

In your HTML, use `{{time.value}}`.

Problem

I have two controllers that have to communicate each other. The first reference to a video player and the second one to a timeline. From the first one, I get the `currentTime` of the video playback and I want to pass it to the second one that should move the time-bar as the video is playing. I tried using the factory to share a variable called `time` between controllers but this doesn't change during the time. First Controller: ``` angular.module('videoCtrl', ['vjs.video']) .controller('videoController', ['$scope', 'Timeline', function (scope, Timeline) { scope.mediaToggle = { sources: [ { src: 'http://static.videogular.com/assets/videos/videogular.mp4', type: 'video/mp4' } ], }; //listen for when the vjs-media object changes scope.$on('vjsVideoReady', function (e, videoData) { videoData.player.on('timeupdate', function () { var time = this.currentTime(); Timeline.setTime(time); // setting the time on factory }) }); }]); ``` Second Controller: ``` angular.module('timelineCtrl', ['mt.media-timeline']) .controller('timelineController', function ($scope, Timeline) { $scope.time = Timeline.getTime(); // here I'm trying to get the time }); ``` Factory: ``` .factory('Timeline', function(){ var timelines = []; var time = null; return { getTime: function() { return time; }, setTime: function(_time) { time = _time; } } }); ```

Original source