0

This is a question I've seen been asked many times before but I can't seem to find a solution that works for me. I have a simple code that updates a loading property and two divs, one that's supposed to be shown when loading is true and one that's shown when loading is false.

    $scope.loading = true;
    function getTasks() {
        $http.get(URL)
            .then(function (response) {
                //success
                $scope.tasks = response.data;
            }
            , function () {
                //failure
                $scope.errorMessage = "Failed to fetch tasks";
                $timeout(getTasks(), 5000); 
            })
            .finally(function () {
                $scope.loading = false;
            });
    }

The HTML is as follows:

    <div ng-show="{{ loading === true }}">
        <i class="fa fa-spinner fa-w-16 fa-spin fa-lg"></i>
    </div>
    <div ng-show="{{ loading === false }}">

However, even though loading does change to false, it doesn't update the view.

Some of the things I've tried are:

  • Using the timeout service

                $timeout(() => {
                    $scope.loading = false;
                });
    
  • Using $scope.$apply() both after changing loading to false and calling a function inside of apply.

  • Adding the getTasks function to the scope.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Danyx
  • 574
  • 7
  • 34
  • As George alluded to, doing `loading === true` or `loading === false` will make your fellow devs laugh at you. Use `loading` and `!loading`, the value is already true or false so all you're doing is slowing down you code by doing a redundant check – BShaps May 15 '18 at 18:05
  • Also, unless you have a good reason for both divs to exist in your DOM at all times, you should use `ng-if` instead of `ng-show` – BShaps May 15 '18 at 18:06

1 Answers1

1

<div ng-show="{{ loading === true }}"> should be <div ng-show="loading === true"> or just

<div ng-show="loading">

loading is a variable defined in your scope. And you can access scope variables as it is in your angular directives ng-show in your case

Muhammad Usman
  • 10,039
  • 22
  • 39