Search code examples
angularjsmvvmangularjs-scopesettimeout

How to pass vm to a setTimeout in AngularJs? Changes to scope don't update DOM view


I'm trying the following code. Everything seems to be working as I see the component appear/disappear depending on the value I set for the variable. However, when I do that in the setTimeout(...) function, it starts to misbehave. The poofy text shows but the value set to vm doesn't. My guess is that I need to pass it in somehow but I'm not sure how.

(function () {
  'use strict';

  angular
    .module("app")
    .controller("Banana", banana);

  function banana() {
    var vm = this;
    vm.showStuff = false;

    setTimeout(function () {
      console.log("poof!");
      vm.showStuff = true;
    }, 1000);
  }
})();

Do I need to make the view-model globally accessible?


Solution

  • Try use the script bellow.

    (function () {
        'use strict';
    
         angular
             .module("app")
             .controller("Banana", banana);
    
         function banana($timeout) {
            var vm = this;
            vm.showStuff = false;
    
            $timeout(function () {
                console.log("poof!");
                vm.showStuff = true;
            }, 1000);
         }
    })();
    

    To be noted - there's additional step required.

    1. Substitute setTimeout(...) for $timeout(...).
    2. Pass $timeout into banana(...).
    3. Provide banana.$inject = ["$timeout",...].