Express+Socket.io實時投票系統(二)

接上一節,這一節,介紹一下Angularjs的安裝
這里前端,我們用bower來安裝,先安裝

npm install -g bower

在工程項目下創建一個.bowerrc文件

{
    "directory": "public/lib"
}

這里以后所有通過bower命令安裝的庫都會放在public/lib目錄下
好了,我們安裝Angular吧

bower install angular
bower install angular-route

這里面安裝了兩個包,一個是angular的主包,一個是angular的路由,因為我們需要跳轉,所以這里需要裝一個angular-route的包
接下來,我們把bootstrap下的css文件拷貝到public的css文件夾下,什么?public下沒有css文件夾?呵呵,因為express-generator創建的工程,public下只創建了stylesheets、javascripts、images三個文件夾,我們為了方便,把stylesheets改成css,javascripts改成js,再創建一個fonts的文件夾,是放bootstrap的fonts的,這里我們就把前端依賴庫安裝好了,
好,接下來,我們在public/js下創建一個app.js,這是我們angular的主文件

angular.module('pollsApp', ['ngRoute', 'controllers', 'pollServices'])
.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/polls', {
            templateUrl: 'js/views/partials/list.html',
            controller: 'PollListCtrl'
        })
        .when('/poll/:pollId', {
            templateUrl: 'js/views/partials/item.html',
            controller: 'PollItemCtrl'
        })
        .when('/new', {
            templateUrl: 'js/views/partials/new.html',
            controller: 'PollNewCtrl'
        })
        .otherwise({
            redirectTo: '/polls'
        });
}]);

這里代碼不多,主要是用了angular的路由功能,對不同的url請求返回不同的頁面和控制器。
接下來要寫服務
在public/js/services下創建一個services.js

'use strict'

angular.module('pollServices', [])
.factory('Poll', function($http, $q){
    return {
        all: function(){
            var delay = $q.defer();
            $http.get('/polls').success(function(response){
                delay.resolve(response);
            }).error(function(){
                delay.reject("Can't get polls data.");
            })
            return delay.promise;
        },
        get: function(pollId){
            var delay = $q.defer();
            $http.get('/poll/' + pollId).success(function(response){
                delay.resolve(response);
            }).error(function(){
                delay.reject("Can't get pollId " + pollId + " data.");
            })
            return delay.promise;
        },
        save: function(poll){
            var delay = $q.defer();
            $http.post('/pollAdd', poll).success(function(){
                delay.resolve();
            }).error(function(){
                delay.reject("Can't save the data.");
            })
            return delay.promise;
        }
    }
});

這里通過angular的工廠生成一個Poll的服務器,這里主要定義了三個方法,一個是獲取全部投票信息的請求,一個是獲取單一投票信息的請求,最后一個就是創建投票信息的請求,這三個請求對應的是后臺創建的三個處理。
這里用了$q來進行promise的處理,當然你也可以不用$q來處理。
接下來在public/js/controllers下創建controllers.js

'use strict'

angular.module('controllers', [])
//投票列表
.controller('PollListCtrl', function($scope, Poll){
    Poll.all().then(function(data){
        $scope.polls = data;
    });
})
//投票詳情
.controller('PollItemCtrl', function($scope, $routeParams, socket, Poll){
    Poll.get($routeParams.pollId).then(function(data){
        $scope.poll = data;
    })
    
    //投票
    $scope.vote = function(){
        
    };
})
//創建新的投票
.controller('PollNewCtrl', function($scope, $location, Poll){
    $scope.poll = {
        question: '',
        choices: [
        { text: '' },
        { text: '' },
        { text: '' }
        ]
    };
    //增加選項
    $scope.addChoice = function(){
        $scope.poll.choices.push({ text: '' });
    };
    //創建投票
    $scope.createPoll = function(){
        var poll = $scope.poll;
        if(poll.question.length > 0){
            var choiceCount = 0;
            poll.choices.forEach(function(choice, index) {
                if(choice.text.length > 0){
                    choiceCount++;
                }
            });
            if(choiceCount > 1){
                var newPoll = $scope.poll;
                Poll.save(newPoll).then(function(){
                    $location.path('polls');
                })
            }else{
                alert('請填寫一個以上選項');
            }
        }else{
            alert('請填寫詳細信息');
        }
    };
});

好了,差不多了,接下來我們在public/js/partials/views下創建三個html頁面
list.html

<div class="page-header">
  <h1>投票列表</h1>
</div>
<div class="row">
  <div class="col-xs-5">
    <a href="#/new" class="btn btn-default"><span class="glyphicon 
glyphicon-plus"></span>創建</a>
  </div>
  <div class="col-xs-7">
    <input type="text" class="form-control" ng-model="query" placeholder="查詢投票信息">
  </div>
</div>
<div class="row">
  <div class="col-xs-12">
    <hr>
  </div>
</div>
<div class="row" ng-switch on="polls.length">
  <ul ng-switch-when="0">
    <li>
      <em>沒有投票信息, 是否要
      <a href="#/new">創建</a>?
    </li>
  </ul>
  <ul ng-switch-default>
    <li ng-repeat="poll in polls | filter:query">
      <a href="#/poll/{{poll._id}}">{{poll.question}}</a>
    </li>
  </ul>
</div>
<p> </p>

item.html

<div class="page-header">
  <h1>投票信息</h1>
</div>
<div class="well well-lg">
  <strong>詳細信息</strong><br>{{poll.question}}
</div>
<div ng-hide="poll.userVoted">
  <p class="lead">請選擇以下一個選項</p>
  <form role="form" ng-submit="vote()">
    <div ng-repeat="choice in poll.choices" class="radio">
      <label>
        <input type="radio" name="choice" ng-model="poll.userVote" value="{{choice._id}}">{{choice.text}}
      </label>
    </div>
    <p><hr></p>
    <div class="row">
      <div class="col-xs-6">
        <a href="#/polls" class="btn btn-default" role="button"><span class="glyphicon glyphicon-arrow-left"></span> 返回</a>
      </div>
      <div class="col-xs-6">
        <button class="btn btn-primary pull-right" type="submit">投票 ?</button>
      </div>
    </div>
  </form>
</div>
<div ng-show="poll.userVoted">
  <table class="result-table">
    <tbody>
      <tr ng-repeat="choice in poll.choices">
        <td>{{choice.text}}</td>
        <td>
          <table style="width: {{choice.votes.length/poll.totalVotes*100}}%;">
            <tr><td>{{choice.votes.length}}</td></tr>
          </table>
        </td>
      </tr>
    </tbody>
  </table>  
  <p>
    <em>共投了{{poll.totalVotes}}票. 
      <span ng-show="poll.userChoice">你投了
        <strong>{{poll.userChoice.text}}</strong>.
      </span>
    </em>
  </p>
  <p><hr></p>
  <p><a href="#/polls" class="btn btn-default" role="button">
  <span class="glyphicon glyphicon-arrow-left"></span> 返回列表</a></p>
</div>
<p> </p>

new.html

<div class="page-header">
  <h1>創建新投票</h1>
</div>
<form role="form" ng-submit="createPoll()">
  <div class="form-group">
    <label for="pollQuestion">詳細信息</label>
    <input type="text" ng-model="poll.question" class="form-control" id="pollQuestion" placeholder="投票詳細信息">
  </div>
  <div class="form-group">
    <label>選項</label>
    <div ng-repeat="choice in poll.choices">
      <input type="text" ng-model="choice.text" class="form-control" placeholder="選項{{$index+1}}"><br>
    </div>
  </div>    
  <div class="row">
    <div class="col-xs-12">
      <button type="button" class="btn btn-default" ng-click="addChoice()"><span class="glyphicon glyphicon-plus"></span> 增加選項</button>
    </div>
  </div>
  <p><hr></p>
  <div class="row">
    <div class="col-xs-6">
      <a href="#/polls" class="btn btn-default" role="button"><span class="glyphicon glyphicon-arrow-left"></span> 返回列表</a>
    </div>
    <div class="col-xs-6">
      <button class="btn btn-primary pull-right" type="submit">創建 ?</button>
    </div>
  </div>
  <p> </p>
</form>

views/index.jade

html
  head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1, user-scalable=no')
    title= title
    link(rel='stylesheet', href='/css/bootstrap.min.css')
    link(rel='stylesheet', href='/css/style.css')
    script(src='lib/angular/angular.min.js')
    script(src='lib/angular-route/angular-route.min.js')
    script(src='/socket.io/socket.io.js')
    script(src='js/app.js')   
    script(src='js/controllers/controllers.js') 
    script(src='js/services/services.js')        
  body(ng-app='pollsApp')
    nav.navbar.navbar-inverse.navbar-fixed-top(role='navigation')
      div.navbar-header
        a.navbar-brand(href='#/polls')= title
    div.container
      div(ng-view)

創建完成后,我們現在運行一下

npm start

訪問http://localhost:3000
如果沒有報錯的話,應該顯示如下:

屏幕快照 2016-10-27 下午5.04.55.png

屏幕快照 2016-10-27 下午5.05.52.png
屏幕快照 2016-10-27 下午5.05.05.png

好了,第二節結束了,第三節,我們為投票系統加入socket.io來進行實時操作。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容