1

i need to use angular $timeout to show element for 2 seconds. it works with $scope but i don't now how to use it with "this" keyword an "controller as ..." syntax.

https://plnkr.co/edit/GPWRg4acYVrP1Ry00D7z?p=preview

angular.module("test", [])
 .controller("testCtrl", function($scope, $timeout){

  $scope.boo = false;

  $scope.disappear = function(){
    $scope.boo = true;
    $timeout(function () {
     $scope.boo = false;
    }, 2000);
  }
});

1 Answers1

2

Do use controllerAs pattern while declaring controller over html like ng-controller="testCtrl as vm". So that vm will have alias of controller basically which will be responsible object make values of this context over HTML for binding.

Markup

<body ng-controller="testCtrl as vm">
  <div>
    <button ng-click="vm.disappear()">button</button>
    <h1 ng-show="vm.boo">Hello Plunker!</h1>
  </div>
</body>

Code

angular.module("test", [])
  .controller("testCtrl", function($timeout) {
    var vm = this;
    vm.boo = false;

    vm.disappear = function() {
      vm.boo = true;
      $timeout(function() {
        vm.boo = false;
      }, 2000);
    }
  });

Demo Plunkr

Additionally I'd also suggest you to place this context inside some variable so that you would not get issue related to this`. Refer this answer for more information

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • thank you very much! you are right. i have tried it but without assigning this to variable and it did not worked. is this have something to do with javascript local ang global scope? – OleGunarSolskier Feb 26 '16 at 21:38
  • @OleGunarSolskier yes..read up on reference answer which I've added there.. THank you.. :) – Pankaj Parkar Feb 26 '16 at 21:39