Reputation: 1298
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
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
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:
Upvotes: 2