Search code examples
javascripthtmlangularjshttp-getauto-update

Updating views on load method + http.get strange behaviour


I have an AngularJS application with different views. One of those views is used to control a tool which has three different states : started, stopped, paused with corresponding buttons.

The tool runs on a server and I want to update the state of my view with the data from the server each time I go back to it. Example : I start the tool, then go to a different view, when I go back on the tool view, I call a service using $http.get to obtain the state of my tool. This returns me a string "started", and i use it to update the elements of my view.

1 - Is it better to use ng-init="update()" in my Tool.html to update at each reload like in :

<div ng-init=update()> [all my content] </div>

or to call update() in my tool controller ? Or maybe another methode you could suggest me.

2 - I tried the two precedent methods, and in each case I have a problem where sometimes, the http.get isn't working and the elements are not correctly actualised. I use it this way :

$http.get('linkToGetTheState')
          .then(function(response) {
              $scope.toolStatus = response.data;
          })
switch($scope.toolStatus)
...

Sometimes it works, other time it doesn't (when I run step by step, it skips everyting from the beginning of the http.get until the end of the switch and toolStatus stays undefined), and even weirder, it works better if I call the function twice... If anyone has any clue on what is happening here and/or why, I would be very thankful.

I hope my question is clear, I'm new to Angular/StackOverflow, and I can give more precisions if needed.


Solution

  • My problem is resolved. Here are the solutions I found :

    1 - I personally prefer to call the update() function in my controller as follow :

    app.controller('MyCtrl', function ($scope, ...) {
        [...]
    
        $scope.update = function() {              
            ...
            });
        };
    
        [...]
    
        $scope.update();
    });
    

    This way, each time the corresponding view is displayed, the function is called once to update it (when changing tabs AND when refreshing the page).

    - 2 For this part, I actually still don't know where the problem really came from. I used the method Gatsbill adviced me here (in the Edit part of his post) : Gatsbill answer to clean/reorganize my project. And with the service to handle $http request, it was working fine.