FrAngular : promise 2
HTML
<script src="http://code.angularjs.org/1.0.0rc2/angular-1.0.0rc2.js"></script>
<div ng-app="app" ng-controller="TweetsCntl">
<h1>Last tweets</h1>
<div id="tweets">
<div class="tweet" ng-repeat="tweet in tweetsData.lastTweets | filter:fullTextSearch | filter:structuredSearch">
<img class="avatar" ng-src="{{tweetsData.user.image}}"/>
<p class="date">{{tweet.created_at | date:'dd/MM/yyyy - hh:mm'}}</p>
<p class="user">{{tweetsData.user.screenName}}
<span class="userid">@{{tweetsData.user.name}}</span></p>
<p class="text" ng-bind-html="tweet.text | linky" />
</div>
</div>
</div>
CSS
body {
background-color: #dadaff;
padding: 15px;
}
h1 {
text-align: center;
}
#filter {
background-color: white;
margin: 1em auto 1em auto;
padding: 1em;
border: solid #aaa 1px;
border-radius: 6px;
}
#tweets {
background-color: white;
margin: 1em auto 1em auto;
padding: 0;
border: solid #aaa 1px;
border-radius: 6px;
}
#tweets div.tweet {
border-bottom: solid #aaa 1px;
padding: 0.7em;
font-family: HelveticaNeue, 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
#tweets div.tweet:last-child {
border-bottom: none;
}
#tweets div.tweet img.avatar {
float: left;
width: 48px;
height: 48px;
margin-right: 10px;
padding: 4px;
}
#tweets div.tweet p {
margin: 0.3em;
padding: 0;
}
#tweets div.tweet p.user {
font-weight: bold;
}
#tweets div.tweet p.user span.userid {
font-weight: normal;
color: grey;
padding-left: 0.5em;
}
#tweets div.tweet p.date {
float: right;
font-size: 0.8em;
color: grey;
}
JavaScript
angular.module('app', []).factory('tweets', function ($q, $http) {
var url, user, lastTweets;
var promiseStart = $q.when('start');
console.log(promiseStart);
var promise1 = promiseStart.then(function (value) {
log("promise0.then");
url = 'http://search.twitter.com/search.json'
+ '?q=angularjs&rpp=100&include_entities=true&result_type=mixed'
+ '&callback=JSON_CALLBACK';
return $http.jsonp(url).
success(function(data, status) {
log("$http1.success");
var lastTweet = data.results[0];
user = {
screenName: lastTweet.from_user,
name: lastTweet.from_user_name,
image: lastTweet.profile_image_url
};
});
});
console.log(promise1);
var promise2 = promise1.then(function (value) {
log("promise1.then");
url = 'https://api.twitter.com/1/statuses/user_timeline.json'
+ '?screen_name='
+ encodeURIComponent(user.screenName)
+ '&callback=JSON_CALLBACK';
return $http.jsonp(url).
success(function(data, status) {
log("$http2.success");
lastTweets = data;
});
});
console.log(promise2);
var promiseEnd = promise2.then(function (value) {
// Success of all the chained requests
log("promise2.then : success");
return {user: user, lastTweets: lastTweets};
}, function (reason) {
// Error in any request
log("promise2.then : error");
return $q.reject(reason);
});
console.log(promise2);
return promiseEnd;
console.log(promise2);
function log(value) {
if (console && console.log) {
console.log(value);
}
}
});
function TweetsCntl($scope, tweets) {
$scope.tweetsData = tweets;
}