简体   繁体   中英

how to properly make a counter angularjs

im trying to make a counter in angularjs, then I'll do something else with this counter, but I need the counter to work first with a var, the problem with this is that the var is not being updated :S, this will be a more complex component so I need it to be a var that can be shown as {{Var}}.

this is how I call the directive on the html

<div test-directive var="5">-</div>

this is the js directive, I tried with link and controller

    app.directive('testDirective',function(){
  return{
    template: '<div> -> {{myLocalVar}} <- </div>',
    scope:{
      specialVar: '=var'
    },
    link: function($scope,element,attributes){
      //console.log($scope.specialVar);
      $scope.myLocalVar = $scope.specialVar;
      //$scope.myLocalVar +=1 ;
      function doThis(){
        $scope.myLocalVar +=1 ;
        //$scope.$digest();
        console.log('in');
        if($scope.myLocalVar < 10){
          setTimeout(function(){doThis();}, 1000);
        }
      }
      doThis();
      //console.log($scope.myLocalVar);
    }
  };
});

Thanks by the help

Try to wrap changes in $apply method callback:

$scope.$apply(function(){
        $scope.myLocalVar +=1;
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM