AngularJS,接口没有按预期更新

时间:2013-03-11 23:08:12

标签: javascript angularjs

我有一个无序列表,当点击每个ListItem时,它会调用setActive()

<li ng-repeat="slide in data" ng-click="setActive(slide.slideIndex)">
  <span class="listItemText">
    <b>{{slide.slideIndex + 1}}. </b>{{slide.Title}}
  </span>
</li>

setActive()是:

$scope.setActive = function(id)
{
    $scope.currentIndex = id;
}

当我点击List Items我更新图片时:

<img id="slide" ng-src="resources/slides/slide{{currentIndex + 1}}.jpg" />

一切正常

什么无效我的视频播放器在某些time我需要更新$scope.currentIndex

我认为这样可行:

player.addEventListener("timeupdate", function()
{
    currentTime = player.currentTime;
    angular.forEach($scope.data, function(value, key)
    {
        if (currentTime >= $scope.data[key].time && currentTime <= $scope.data[key].time + 0.3 && $scope.currentIndex != key)
        {
            console.log("load id:" + key);
            $scope.setActive(key); //Calling what works when I click a listItem
        }
    });
});

console.log工作并在提示点记录,但是,在我MouseOver列表之前,图像不会更新。此时,图像将更新为$scope.currentIndex恰好是什么。我完全迷失了。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

因为您在典型的Angular执行上下文之外更新模型,所以需要使用scope。$ apply()以便Angular知道它需要运行$ digest并可能更新视图。在此处查看有关$ apply的更多信息:

$rootScope.Scope.$apply

基本上,如果你在$ apply中调用setActive,那么Angular会知道它需要更新视图。这应该可以解决问题:

player.addEventListener("timeupdate", function()
{
    currentTime = player.currentTime;
    angular.forEach($scope.data, function(value, key)
    {
        if (currentTime >= $scope.data[key].time && currentTime <= $scope.data[key].time + 0.3 && $scope.currentIndex != key)
        {
            console.log("load id:" + key);

            // Wrap the call in $apply so Angular knows to call $digest
            $scope.$apply(function() {
                $scope.setActive(key);
            });
        }
    });
});