angularjsangularjs-scopeangularjs-controllerangularjs-ng-clickangularjs-timeout

In an Angular.js controller's scope function code doesn't run below a $timeout statement inside


I have a button for which I have set ng-click="refresh()". The console logs before the timeout function logs correctly but the console log inside the $timeout block and after the block doesn't seem to log. If I remove the $timeout block every console log works. I even checked with $interval instead of $timeout but same behaviour.

I wanted to do something like this here

I'm using Angular.js 1.4.0

This is my implementation inside the controller

      $scope.refreshing ={state: false};
      $scope.refresh = function(){
        console.log($scope);
        $scope.refreshing.state = true;
        $scope.search(); //sends an http request and loads results.
        console.log('this logs');
        // $scope.refreshing.state = false;
        $timeout(function(){
           console.log('this doesnt log')
           $scope.refreshing.state = false;
         },2000);
        console.log('this doesnt log')

      }

Solution

  • You'll want to make sure your dependency injection is wired up properly. For example:

    angular
        .module("MyApp")
        .controller("MyController", ["$scope", "$timeout", MyController]);
    
    function MyController($scope, $timeout) {
        // controller code
    }
    

    See John Papa's AngularJS style guide for some best practices relating to controllers.