-1

There is a factory

  httpFactory.factory('setRating', function($http){
        return{
            Like: function(id){
                return $http.get('http://localhost:51265/Film/Like/' + id);
            }
        }
    });

In the controller

$scope.thisLike = function(id){
        setRating.Like(id).then((response) => {
            $('.rating-count').text(response.data);
        })
    }

It seems to be quite normal and works as it should. But I'm confused by this binding to the class of the element. I want to use it this way

<button  
                        class="fa fa-thumbs-up like" 
                        ng-click="rating=thisLike(film.FilmId);"></button>
                <div>
                    <span ng-class="{'low-rating':rating < 0}" 
                          class="rating-count">{{ rating }}</span>
                </div>
                <button  
                        class="fa fa-thumbs-down dislike" 
                        ng-click="rating=thisDisLike(film.FilmId)"></button>

That is, initialize a local variable in the markup and assign it to the one that returns the method. But the problem is that I trivial can not return the correct meaning.

I tried it so

    $scope.thisLike = function(id){
      let v = 0;
        setRating.Like(id).then((response) => {
            v = response.data;
        })
      return v;
    }

but the method returns immediately and do not wait until I get the value. The question is how to postpone the return until I get the meaning from the promise. I get 0

Саске
  • 190
  • 3
  • 12

1 Answers1

1

So first of all, why you are using jQuery there? There is no jquery needed!

"but the method returns immediately"

This is the correct behavior, your Promise (the http call) is async.

So what you might want is this:

$scope.rating = 0
$scope.thisLike = function(id){

    setRating.Like(id).then((response) => {
        $scope.rating = response.data;
    })
}
enno.void
  • 6,242
  • 4
  • 25
  • 42