gpt4 book ai didi

javascript - 每个指令都有独特的计时器

转载 作者:行者123 更新时间:2023-12-03 06:24:25 26 4
gpt4 key购买 nike

我对 Angular 还很陌生。我有我的指令,我想为每个对象执行我的timer() 函数。

我的 Controller 与数据:

app.controller("cardsCtrl", function($scope, $interval){

$scope.changeTire = {
name: 'Change Tire',
timer: 16
};
$scope.fixTire = {
name: 'Fix Tire',
timer: 30
};

function timer(){
$interval(function(){
if($scope.countDown>0){
$scope.countDown--;
$scope.cardAnimation = {'width': +($scope.countDown/fullTimer*100)+'%' }
}
},1000,0);
}

});

我的指令:

<div class="card">
<span class="name">{{cardInfo.name}}</span>
<span class="time">{{cardInfo.timer }}</span>
<div class="card-inner" ng-style="cardAnimation" ng-hide="finishCard"></div>
</div>

var app = angular.module("cards", ['ngAnimate']);

app.directive("card", function(){
return{
restrict: 'E',
scope: {
cardInfo: '=info'
},
templateUrl: 'card.html'
};
});

和 html

<div ng-app="cards" ng-controller="cardsCtrl">
<card info="changeTire" ></card>
<card info="fixTire" ></card>
</div>

最佳答案

实现此目的的一种方法是将函数作为回调传递给指令并在指令中执行该函数。

Controller :

 app.controller("cardsCtrl", function($scope, $interval){

$scope.changeTire = {
name: 'Change Tire',
timer: 16,
timerFunction: timerFunct
};
$scope.fixTire = {
name: 'Fix Tire',
timer: 30,
timerFunction: timerFunct
};

function timerFunct(){
$interval(function(){
if($scope.countDown>0){
$scope.countDown--;
$scope.cardAnimation = {'width': +($scope.countDown/fullTimer*100)+'%' }
}
},1000,0);
}

});

并在指令中:

app.directive("card", function(){
return{
restrict: 'E',
scope: {
cardInfo: '=info'
},
templateUrl: 'card.html',
link: function(scope){
scope.cardInfo.timerFunction()
}
};
});

而不是上面的代码这样做。

Controller :

app.controller("cardsCtrl", function ($scope, $interval) {

$scope.changeTire = {
name: 'Change Tire',
timer: 16
};

$scope.fixTire = {
name: 'Fix Tire',
timer: 30
};
});

并在指令中:

app.directive("card", function () {
return {
restrict: 'E',
scope: {
cardInfo: '=info'
},
templateUrl: 'card.html',
link: function (scope) {
timerFunct(scope.cardInfo.timer);

function timerFunct(timer) {
$interval(function () {
if (timer > 0) {
timer--;
$scope.cardAnimation = { 'width': +(timer / fullTimer * 100) + '%' }
}
}, 1000, 0);
}
}
};
});

关于javascript - 每个指令都有独特的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com