我对角度很新。我有我的指令,我想为每个对象执行我的timer()函数。
我的控制器包含数据:
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>
答案 0 :(得分:1)
执行此操作的一种方法是,将函数作为回调函数传递给指令并在指令中执行该函数。
控制器:
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()
}
};
});
代替上面的代码执行此操作。
控制器:
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);
}
}
};
});