Freddy Bonda
Freddy Bonda

Reputation: 1259

AngularJS Update DOM

Could someone explain to me how to get the DOM to "refresh" it's values in AngularJS? Here is an example of what I am trying to achieve.

The button starts out disabled, and after 3s I want it to be enabled. My code does enabled the variables correctly, but the ng-disabled is not refreshing. How can I fix this?

I have read up about $apply but many people say it is tricky to understand and dangerous to use. I myself cannot $apply to work (I won't really understand it)

You are welcome to refer me to other questions as I am sure this problem is nothing new.

  <button ng-disabled="!Check1 || !Check2">Disabled</button>
  ...
  $scope.Check1 = false;
  $scope.Check2 = true;
  setTimeout(() => {
    $scope.Check1 = true;
    alert('Check1 now true');
  }, 3000);

http://plnkr.co/edit/O7j89xoS8rHCTz1Fn2pG?p=preview

*NOTE: Don't refer me to $timeout. The timeout here is just an example of a delayed response which could be anything.

Upvotes: 2

Views: 1999

Answers (1)

Freddy Bonda
Freddy Bonda

Reputation: 1259

This is quite easy I see now. Just wrap the value change in $scope.$apply like below:

  <button ng-disabled="!Check1 || !Check2">Disabled</button>
  ...
  $scope.Check1 = false;
  $scope.Check2 = true;
  setTimeout(() => {
    $scope.$apply(function () {
      $scope.Check1 = true;
      alert('Check1 now true');
    });
  }, 3000);

This article was really helpful in solving this: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Upvotes: 1

Related Questions