AngularJS - 在两个控制器之间共享变量

Ang*_*ons 3 angularjs

我有两个控制器必须相互通信.第一个引用视频播放器,第二个引用时间线.

从第一个开始,我得到了currentTime视频播放的内容,我希望将其传递给第二个应该在播放视频时移动时间栏的视频.

我尝试使用工厂共享一个time在控制器之间调用的变量,但这在此期间不会改变.

第一控制员:

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
          })
        });
    }]);
Run Code Online (Sandbox Code Playgroud)

第二控制器:

angular.module('timelineCtrl', ['mt.media-timeline'])
    .controller('timelineController', function ($scope, Timeline) {
    $scope.time = Timeline.getTime(); // here I'm trying to get the time
  });
Run Code Online (Sandbox Code Playgroud)

工厂:

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

      getTime: function() {
        return time;
      },

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

    }
  });
Run Code Online (Sandbox Code Playgroud)

Cla*_*ies 5

time似乎是一个原始的,这意味着它是由VAL而不是byRef返回的.换句话说,每次调用都getTime将返回time当前设置的值,并且调用setTime将更改未来调用的值,但不会更改已调用它的任何值.这是角度规则的经典案例,始终使用点.

请尝试更改time为对象:

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

    getTime: function() {
      return time;
    },

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

  }
});
Run Code Online (Sandbox Code Playgroud)

在您的HTML中,使用{{time.value}}.