Last Updated: September 09, 2019
·
1.734K
· xvfeng

Hacker Weibo with Angular JS

Picture

看了AngularJS的相关概念已经有一个多星期了,所以决定尝试真正用它来写点小的Demo。

例子很简单,没有什么特别复杂的东西。调用了新浪微博的API来获取自己和关注好友的最新微博。

The JavaScript

首先写一个Controller来调用数据。这里使用新浪微博的API.(个人觉得新浪微博的API是国内大型社交网站中做的比较好的了。)

# app.js

// 用于显示微博列表的Controller
function WeiboListCtrl($scope, $http) {
    $http.jsonp('https://api.weibo.com/2/statuses/friends_timeline.json?callback=JSON_CALLBACK&access_token=2.00YwP8sBGoDixB537b1199b20i7RQn').success(function(data) {
    $scope.statuses = data.data.statuses;
    });
}

The HTML

<!doctype html>
<html lang="en" ng-app="hn">

<head>
    ....

</head>


<body ng-controller="TopListCtrl">

<header>
    <div class="container">
        <h1 class="logo">Hacker News</h1>
    </div>
</header>


<div class="container content">
    <ul class="posts">
        <li ng-repeat="statuse in statuses">
            {{ statuse.text }}
            <!-- <span class="url">{{ statuse.source | userSource}}</span> -->
            <small> {{ statuse.created_at | fromDate }} by <a href="{{ statuse.user.domain | userURL }}">{{ statuse.user.screen_name }}</a> {{ statuse.reposts_count }} reposts | {{ statuse.comments_count }} comments from {{ statuse.source | userSource}}</small>
        </li>
    </ul>
</div>

</body>
</html>

上面所做的就是使用Angular JS提供的ng-repeat来遍历我们所得到的Statuses对象,然后分别显示具体内容。

Filters?

好了 - 只要了不到5分钟。但是这里我还要加一些东西,用来优化页面的显示内容。

首先是用户的个人主页。新浪API默认返回的对象里面只有domain,也就是用户的自定义url,但是没有完整的个人链接。这里也就是http://weibo.com/xvfeng123,所以我需要编写一个filter来对结果进行处理。

filter('userURL', function() {
  return function(text, length, end) {
    return 'http://weibo.com/' + text
  };
})

同样,接下来处理微博消息来源以及时间。处理时间我这里使用了著名的momentjs,这是一个相当强大的用于格式化日期的js库,强烈推荐。最后就是用正则来替换微博消息来源了。

微博默认的格式为<a href=\"http://weibo.com/\" rel=\"nofollow\">新浪微博</a>,但这里我需要的不是一个链接,而是一个简单的文字。所以我这里需要一个处理来源的filter.

filter('userSource', function() {
  return function(text, length, end) {
    return text.replace(/<[^>]+?>/g,"")
  };
})

最后,我们只要在页面的其他地方分别引入代码就可以了。

好了,一个简单的Hack Weibo就是这样了。

最后给上完整DEMO地址

2 Responses
Add your response

i am also about to demo weibo with angular... cheers

over 1 year ago ·

DEMO 地址 403 - Forbidden

over 1 year ago ·