AngularJS Scope not updating in view after async call

前端 未结 3 982
离开以前
离开以前 2020-12-18 21:23

I am having trouble updating my scope on the front-end while making a request to an API. On the backend I can see that the value of my $scope variable is changing but this i

3条回答
  •  旧时难觅i
    2020-12-18 21:38

    I you are using AngularJS 1.3+, you can try $scope.$applyAsync() right after $scope.beers = response.data; statement.

    This is what Angular documentation says about $applyAsync()

    Schedule the invocation of $apply to occur at a later time. The actual time difference varies across browsers, but is typically around ~10 milliseconds. Source

    Update

    As others have pointed out, you should not (usually) need to trigger the digest cycle manually. Most of the times it just points to a bad design (or at least not an AngularJS-friendly design) of your application.

    Currently in the OP the fetch method is triggered on $watch. If instead that method was to be triggered by ngChange, the digest cycle should be triggered automatically.

    Here is an example what such a code might look like:

    HTML

    // please note the "controller as" syntax would be preferred, but that is out of the scope of this question/answer
    
    

    JavaScript

    function SearchController($scope, $http) {
    
        $scope.search = "Sherlock Holmes";
    
        $scope.fetchBeers = function () {
            const query = `http://api.com/v2/search?q=${$scope.search}&key=[API KEY]&format=json`;
            $http.get(query).then(response => $scope.beers = response.data);
        };
    
    }
    

提交回复
热议问题