Raf A.
Raf A.

Reputation: 126

Reloading Controller in Angular

I am a newbie in angular, and I haven't been able to find any solid answers for this question... even though the answer might have been in front of me, I just couldn't see it.

I have this piece of html:

<ul class="wrapper" ng-controller="MyController as vks">
    <li ng-repeat="myvar in vks.vk" class="padding-left" data-myvar-id="{{myvar.id}}">
      <img src="images/someimage.svg" ng-show="{{myvar.id}} == {{myvar.chosen}}" class="some-class">
      <a class="hvr-underline-reveal">{{myvar.name}}</a>
    </li>
  </ul>

And this is my controller:

  app.controller('MyController',  function() {

    var i = 0;
    var tmp = [];
    for (var key in someObject) {
      if (someObject.hasOwnProperty(key)) {
        var obj = someObject[key];
        if (obj.checked) {
          tmp[i] = {name: obj.name, id: obj.id, chosen: someStaticVar};
          i++;
        }
      }
    }
    this.vk = tmp;

  });

I want to focus on this part which works the first time the page is loaded:

<img ng-show="{{myvar.id}} == {{myvar.chosen}}">

What happens when suddenly {{myvar.chosen}} (which is is set from a static global var) changes from some outside javascript? The HTML part is not refreshed, and that specific is still shown, but it should be another one shown. How can I reload only this controller? (or do something else to make this work as intended?)

Hope this makes sense...

Upvotes: 0

Views: 66

Answers (2)

digitil
digitil

Reputation: 919

As @Jodevan hinted, Angular will not be aware of the change to the global variable. But even if it was made aware of that change, based on your example, your view still wouldn't update since the value of the bound variable myvar.chosen is not changing. In other words, your for-loop is not being reevaluated when that global variable changes.

To get your desired effect, you would have to (1) know when the global variable has changed and (2) update the value of the chosen property so that the model actually changes and triggers a digest.

Here's a fiddle showing how the code above could be made to work: naive solution. Hopefully, knowing the 2 requirements above, you can come up with a solution that works for you.

Upvotes: 1

Jodevan
Jodevan

Reputation: 750

Whenever you change a variable not directly through AngularJS, you must let AngularJS knows that this variable was changed. The way to do that is using the scope.$apply() function. I think this can help you to understand what is going on under the hood.

Upvotes: 1

Related Questions