Angular ui 轮播和指令范围问题

Angular ui carousel and directive scope issues

我创建了一个简单的 Plunker 来演示这个问题。

我有一个独立范围的指令,它每秒更新一次以增加本地计时器。我原以为隔离范围不会影响其他任何东西。

在 Plunker 示例中,我可以看到父范围值没有被更新,但是轮播每隔一秒就会更新 'refreshed'。抱歉,如果这不是正确的 angular 术语,但我仍在学习。

这是我的指令代码:

app.directive('timer', ['$interval', function ($interval) {

    function link(scope, element, attrs) {
        var timeoutId;

        element.on('$destroy', function () {
            $interval.cancel(timeoutId);
        });

        // start the UI update process; save the timeoutId for canceling
        timeoutId = $interval(function () {
            scope.seconds++;
        }, 1000);
    }

    return {
        link: link,
        scope: {
            seconds: '@'
        },
        template: '<div>Isolated: {{seconds}}</div>'

    };
}]);

如何确保计时器不会导致轮播刷新?

您的 Plunker 中有些地方看起来不对。

  1. 像这样绑定一个函数是个坏主意。 <p>{{hurro()}}</p>

  2. 我不使用指令来制作计时器。 $interval 已经为你计时了。你可以像这样修改你的js脚本。 完全删除计时器指令,将 $interval 添加到控制器,并从我添加的 Repeat 函数中调用 hurro。
    您会看到 hurro() 独立于 Carousel 刷新被调用。

    function CarouselDemoCtrl($scope, $interval) {
      $scope.myInterval = 0;
      $scope.called=0;
      $scope.called2=0;
      $scope.mySeconds=10;
      var slides = $scope.slides = [];
      $scope.addSlide = function() {
        var newWidth = 600 + slides.length;
        slides.push({
          image: 'http://placekitten.com/' + newWidth + '/300',
          text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
            ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
        });
      };
      for (var i=0; i<4; i++) {
        $scope.addSlide();
      }
    

    $scope.hurro = 函数() { $scope.called = $scope.called+1; $("#called").html($scope.called); }

          var refresh;
        $scope.Repeat = function () {
            refresh = $interval(function () {
                console.log("refresh at " + new Date().toString());
                $scope.hurro();
            }, 1000);
        }
        $scope.Repeat();
    

    }

我终于弄明白了。问题不是轮播,而是导致 $rootScope.$apply() 的 $interval 计时器。

$interval 签名是函数 interval(fn, delay, count, invokeApply) 因此将 invokeApply 传递为 false 可以防止这种情况发生。