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 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 yes..read up on reference answer which I've added there.. THank you.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.