AngularJS:service $ broadcast和$ watch在接收控制器上没有触发

时间:2012-10-17 07:02:16

标签: javascript angularjs

AngularJS noob在我的角色启蒙之路上:)

情况如下:

我已在我的模块'app'中实现了一个服务'AudioPlayer'并注册如下:

 app.service('AudioPlayer', function($rootScope) {

     // ...

     this.next = function () {
         // loads the next track in the playlist
         this.loadTrack(playlist[++playIndex]);     
     };

     this.loadTrack = function(track) {
         // ... loads the track and plays it
         // broadcast 'trackLoaded' event when done
         $rootScope.$broadcast('trackLoaded', track); 
     };
 }

这里是'接收器'控制器(主要用于UI /表示逻辑)

app.controller('PlayerCtrl', function PlayerCtrl($scope, AudioPlayer) {


    // AudioPlayer broadcasts the event when the track is loaded

    $scope.$on('trackLoaded', function(event, track) {
        // assign the loaded track as the 'current' 
        $scope.current = track;
    });

    $scope.next = function() {
        AudioPlayer.next();
    };
}

在我的观看中,我会显示当前的曲目信息:

<div ng-controller="PlayerCtrl">
    <button ng-click="next()"></button>
    // ...
    <p id="info">{{current.title}} by {{current.author}}</p>
</div>

next()方法在PlayerCtrl中定义,它只是在AudioPlayer服务上调用相同的方法。

问题

当有手动交互时(即当我点击下一个()按钮时),此工作正常 - 流程如下:

  1. PlayerCtrl拦截点击并触发自己的next()方法
  2. 反过来触发AudioPlayer.next()方法
  3. 搜索播放列表中的下一首曲目并调用loadTrack()方法
  4. loadTrack()$广播'trackLoaded'事件(用它发送曲目本身)
  5. PlayerCtrl侦听广播事件并将轨道分配给当前对象
  6. 视图正确更新,显示current.title和current.author info
  7. 但是,当在“背景”中的AudioService内调用next()方法时(即,当轨道结束时),会发生从1到5的所有步骤,但视图不会得到通知PlayerCtrl的'当前'对象的变化。

    我可以清楚地看到在PlayerCtrl中分配的新轨道对象,但就好像视图没有得到更改通知。我是一个菜鸟,我不确定这是否有任何帮助,但我尝试过在PlayerCtrl中添加$ watch表达式

    $scope.$watch('current', function(newVal, oldVal) {
        console.log('Current changed');
    })
    

    仅在“手动”互动中打印出来......

    再次,就像我说的,如果我在$ on侦听器中添加一个console.log(当前),就像这样:

    $scope.$on('trackLoaded', function(event, track) {
        $scope.current = track;
        console.log($scope.current);
    });
    

    始终正确打印。

    我做错了什么?

    (ps我正在使用AudioJS作为HTML5音频播放器,但我认为这不应该归咎于此......)

4 个答案:

答案 0 :(得分:21)

如果您有点击事件,$ scope会更新,如果没有事件,您需要使用$ apply

$scope.$apply(function () {
    $scope.current = track;
});

答案 1 :(得分:7)

因为查看摘要内部结构是不安全的,最简单的方法是使用$timeout

$timeout(function () {
    $scope.current = track;
}, 0);

回调总是在良好的环境中执行。

编辑:事实上,应该包含在应用阶段的功能是

 this.loadTrack = function(track) {
     // ... loads the track and plays it
     // broadcast 'trackLoaded' event when done
     $timeout(function() { $rootScope.$broadcast('trackLoaded', track); });
 };

否则广播将被遗漏。

~~~~~~

实际上,替代方案可能更好(至少从语义的角度来看)并且它将在摘要周期内部或外部同等地工作:

$scope.$evalAsync(function (scope) {
    scope.current = track;
});
  • 关于$scope.$apply的优势:您不必知道自己是否处于消化周期中。
  • 关于$timeout的优势:您实际上并不想要超时,并且您可以在没有额外0参数的情况下获得更简单的语法。

答案 2 :(得分:0)

// apply changes
$scope.current = track;
try {
 if (!$scope.$$phase) {
  $scope.$apply($scope.current);
 }
} catch (err) {
 console.log(err);
}

答案 3 :(得分:0)

尝试了一切,$rootScope.$applyAsync(function() {});

对我有用