2016-07-20 5 views
0

ディレクティブを使ってカウントダウンタイムを作成したいのですが、時間が変化しているときにフェードアウトのようなCSSスタイルを追加する必要があります。私の問題はhtmlバインディングにあります。ここでカウントダウン時間はどのように更新できますか?

私のHTML

<body ng-app="myApp" ng-controller="myCtrl"> 
<count-down-timer count-down-time=5000></count-down-timer> 
{{userCountDownTime}} 
</body> 

は、ここであなたは何かが変更されたangularJSに通知する必要があり、私のJSコード

app.directive('countDownTimer', function() { 
return { 
restrict: 'E', 
replace: true, 
link: function (scope, elem, attr) { 
    scope.userCountDownTime = attr.countDownTime; 
    initiate(); 
    function initiate() { 
    console.log("initiated") 
    var myVar = setInterval(decreament, 1000); 
    }; 

    function decreament() { 
    console.log("decreament"); 
    scope.userCountDownTime--; 
    console.log(scope.userCountDownTime); 
    return; 
    } 
} 
}}); 
+0

https://docs.angularjs.org/api/ng/service/$intervalこの方法では、ダイジェストサイクルをトリガーしてコールバック関数でバインドされたパラメータが変更された場合、ビューを更新するように角度を「知っています」 –

答えて

1

で変更することができます。

https://plnkr.co/edit/FSOtUYcoPhLEwp5paNin?p=preview

.directive('countDownTimer', function ($interval) { 
return { 
restrict: 'E', 
replace: true, 
link: function (scope, elem, attr) { 
    scope.userCountDownTime = attr.countDownTime; 
    initiate(); 
    function initiate() { 
    console.log("initiated") 
    var myVar = $interval(decreament, 1000); 
    }; 

あなたはオーバーラッパーです$間隔のサービスを追加する必要がありますwindow.setInterval https://docs.angularjs.org/api/ng/service/ $ interval

1

です。 $scope.$applyに電話する必要があります。 $intervalを使用すると、安全に実行できます。

app.directive('countDownTimer', function ($interval) { 
    return { 
    restrict: 'E', 
    replace: true, 
    link: function (scope, elem, attr) { 
     scope.userCountDownTime = attr.countDownTime; 

     $interval(decrement, 1000); 

     function decrement() { 
      scope.userCountDownTime--; 
     } 
    } 
}}); 

EDIT:$ timeoutの代わりに$ intervalを使用するように修正されました。

+1

'$ interval 'を使って関数を単に起動させるべきときに' $ timeout'を呼び出す際の余分な値 –

+0

あなたは正しいです、私の答えを修正しました。 –

+1

今はるかに良い:) –

0

だからあなたのディレクティブは、あなたがplunkrで見ることができ

app.directive('countDownTimer', [ '$interval', function ($interval) { 
return { 
restrict: 'E', 
replace: true, 
link: function (scope, elem, attr) { 
    scope.userCountDownTime = attr.countDownTime; 
    initiate(); 
    function initiate() { 
    console.log("initiated") 
    var myVar = $interval(decreament, 1000); 
    }; 

    function decreament() { 
    console.log("decreament"); 
    scope.userCountDownTime--; 
    console.log(scope.userCountDownTime); 
    return; 
    } 
} 
}}]); 
関連する問題