Marco Prado
Marco Prado

Reputation: 1298

$http get not refreshing result

I am Trying to do some examples with angularJS:

Html:

<html ng-app="myApp">
    <body ng-controller="JokesController">
        <h1>{{ joke }}<h1>
    </body>
</html>

Script:

<script type="text/javascript">

    m.factory('$jokeService', function($http, $interval) {

        var service = {
            joke: ""
        };

        service.randomize = function () {
            $http.get("http://api.icndb.com/jokes/random")
                .success(function(data) { 
                    service.joke = data.value.joke;  
                    console.log(service.joke)
                })
                .error(function(data) {
                    console.log(data)
                });
        }

        $interval(function() {
            service.randomize();
        }, 2000)

        return service;
    });

    m.controller('JokesController', function($scope, $jokeService) {
        $scope.joke = $jokeService.joke;
    });
</script>

The joke value is not shown in the html. Am I missing something?

Upvotes: 1

Views: 129

Answers (2)

scniro
scniro

Reputation: 16979

You need to resolve the factory returned promise in your controller. We can simplify your service as well by moving the resolution logic and changing injections. Observe the following change...

.factory('$jokeService', function($http) {
    function getJoke() {
        return $http.get('http://api.icndb.com/jokes/random');
    }

    return {
        getJoke: getJoke
    };
});

.controller('JokesController', function($scope, $jokeService, $interval) {

    $interval(function() {
        $jokeService.getJoke().then(function(response) {
            $scope.joke = response.data.value.joke;
        });
    }, 2000);
 });

Plunker Link - working demo

Upvotes: 2

Steve Kl&#246;sters
Steve Kl&#246;sters

Reputation: 9457

The value of $jokeService.joke is copied once in the controller at $scope.joke = $jokeService.joke;. To bind to the value that keeps changing, set $scope.service = $jokeService and change the binding in HTML to service.joke.

For your visualisation, this is what happens:

  • AngularJS attempts to create the controller, but finds the service dependency
  • AngularJS creates and runs the service
  • AngularJS creates and runs the controller (the value gets copied here)
  • The controller's scope is attached to the HTML element

Upvotes: 2

Related Questions