AngularJS Scope not updating in view after async call

前端 未结 3 979
离开以前
离开以前 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条回答
  •  盖世英雄少女心
    2020-12-18 21:41

    As the comments suggest, you shouldn't need to use $timeout to trigger a digest cycle. As long as the UX that elicits the change is within the confines of an angular construct (e.g. controller function, service, etc.) then it should manifest within the digest cycle.

    Based on what I can infer from your post, you are probably using a search input to hit an API with results. I'd recommend changing the logic up such that you are triggering your search on an explicit event rather than the $watcher.

    
    

    Remove the $watch logic and the $timeout wrapper.

    function fetch(){
        var query = "http://api.com/v2/search?q=" + $scope.search + "&key=[API KEY]&format=json";
    $http.get(query)
    .then(function(response){ 
        $scope.beers = response.data; 
        console.log($scope.beers);
    
        //it's a good habit to return your data in the promise APIs
        return $scope.beers;  
    });
    }
    

    The reasons I make this recommendation is:

    • You have finer control of how the ng-change callback is triggered using ng-model-options. This means you can put a delay on it, you can trigger for various UX events, etc.
    • You've maintained a clearer sequence of how fetch is called.
    • You have possibly avoided performance and $digest issues.

提交回复
热议问题