Higeath Higeath - 4 months ago 7
AngularJS Question

Unique timer for each directive

I am quite new to angular. I have my directive and I would want to execute my timer() function for each object.

My controller with data:

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

});


My directive:

<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'
};
});


And the html

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

Answer

one way to do this is, pass function as callback to the directive and execute that function in directive.

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

});

and in directive :

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

instead of above code do this.

Controller:

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

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

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

and in directive:

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