2016-08-22 39 views
0

我創建了一個簡單的Plunker來演示此問題。Angular UI旋轉木馬和指令範圍問題

我有一個隔離範圍的指令,每隔一秒更新一次以增加一個本地定時器。我期待孤立的範圍不會影響其他任何東西。

在Plunker的例子中,我可以看到父母的範圍值沒有被更新,但是每一秒輪播被刷新。道歉,如果這不是正確的角度術語,但我還在學習。

這是我的指令代碼:

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>' 

    }; 
}]); 

如何確保定時器不會導致轉盤的刷新?

+1

旋轉木馬刷新方式是什麼?當我運行猛擊隊員時,一切看起來都很正常。 – plong0

+0

hurro()函數是每秒調用一次的benig,被調用的函數會遞增並顯示在傳送帶下方。 –

回答

0

我終於得到了這條底線。問題不是傳送帶,而是引起$ rootScope。$ apply()的$ interval計時器。

$ interval簽名是函數間隔(fn,delay,count,invokeApply),因此將invokeApply作爲false傳遞以防止發生此情況。

1

有些東西看起來不合適您的Plunker。

  1. 綁定這樣的函數是一個壞主意。 <p>{{hurro()}}</p>

  2. 我不使用指令來製作計時器。 $美元的時間間隔已經爲你做好時機你可以像這樣修改你的js腳本。 完全刪除timer指令,將$ interval添加到您的控制器,並從我添加的Repeat函數調用hurro。
    你會看到獨立於Carousel刷新調用hurro()。

    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(); 
    

    }

+0

1.功能是突出問題2.定時器指令是一個非常簡化的版本來說明問題。 –

+0

我不確定是什麼原因引起的問題2,但我能夠輕鬆地複製它。該櫃檯每秒增加約10次。我的猜測是你無意中做了一個遞歸循環,或者Angular每秒鐘多次觀看範圍變化和/或Web事件。 –