2016-03-20 7 views
0

Я работал над созданием страницы комментариев на основе https://thinkster.io/mean-stack-tutorial. Но страница не появляется вообще. Вот код:MEAN Stack: Страница не отображается вообще

В index.ejs в просмотров каталог:

<!DOCTYPE html> 
<html> 
<head> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"/> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> 
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script> 
    <script src="/javascripts/ang.js"></script> 
</head> 
<body ng-app="peopleComments"> 
<script type="text/ng-template" id="/home.html"> 
    <div class="container"> 
    <div class="row"> 
    <div class="col-md-8 col-md-offset-2"> 

    <div class="page-header"> 
     <h2>Learn. Share. Popularize.</h2> 
    </div> 
     <p>Share here to let the world know.</p> 
     <hr/> 
    <div ng-repeat="comment in comments|orderBy:'-upvotes'" style="line-height:25px"> 
     {{comment.username}} - {{comment.contents}} 
     <br> 
     {{comment.upvotes}} 
     <span class="glyphicon glyphicon-triangle-top" ng-click="increaseUpvotes(comment)" style="color:green"></span> &nbsp;&nbsp; 
     {{comment.downvotes}} 
     <span class="glyphicon glyphicon-triangle-bottom" ng-click="increaseDownvotes(comment)" style="color:red"></span> 
     <hr/> 
    </div> 
    <form ng-submit="addComment()"> 
     <div class="col-xs-2"> 
     <div class="form-group"> 
      <input type="text" class="form-control" placeholder="Your Name" ng-model="username"></input> 
     </div> 
     </div> 
     <div class="col-xs-8"> 
     <div class="form-group"> 
      <input type="text" class="form-control" placeholder="What would you like to share?" ng-model="contents"></input> 
     </div> 
     </div> 
     <button class="btn btn-info" type="submit">Add My Entry</button> 
    </form> 
    </div> 
    </div> 
    </div> 
</script> 
</body> 
</html> 

В comments.js в модели каталог:

var mongoose = require('mongoose'); 

var CommentSchema = new mongoose.Schema({ 
username: String, 
contents: String, 
upvotes: {type: Number, default: 0}, 
downvotes:{type:Number, default:0} 
}); 
CommentSchema.methods.upvote=function(cb){ 
this.upvotes+=1; 
this.save(cb); 
}; 
mongoose.model('Comment', CommentSchema); 

В анг .js в public/javascript s каталог:

var app=angular.module('peopleComments',['ui.router']); 
app.factory('comments',['$http', function($http){ 
var c={ 
comments:[] 
}; 

//loading all existing comments with getAll() 
c.getAll=function(){ 
return $http.get('/comments').success(function(data){ 
    angular.copy(data, c.comments); 
}); 
}; 

//function which creates the new comments for updating in the database 
c.create = function(comment) { 
return $http.post('/comments', comment).success(function(data){ 
c.comments.push(data); 
}); 
}; 

app.config([ 
'$stateProvider', 
'$urlRouterProvider', 
function($stateProvider, $urlRouterProvider) { 

//setting up a home state 
$stateProvider 
.state('home', { 
    url: '/home', 
    templateUrl: '/home.html', 
    controller: 'Base', 
    resolve: { 
     comment: ['comments', function(comments){ //using resolve property of ui-router - not rendering??? 
      return comments.getAll(); 
    }] 
    } 
}); 

$urlRouterProvider.otherwise('home'); 
}]); 

app.controller('Base',[ 
'$scope','comments',function($scope,comments){ 
    $scope.addComment=function(){ //add new comments to the server/display existing ones 
     $scope.comments=comments.comments; 
     if(!$scope.username||$scope.username=='') {$scope.username='Anonymous';} 
     if(!$scope.contents||$scope.contents==''){return;} 
      comments.create({ 
      username: $scope.username, 
      contents: $scope.contents, 
      }); $scope.comments.push({username:$scope.username,contents:$scope.contents,upvotes:0,downvotes:0}); 
     $scope.username=''; 
     $scope.contents=''; 
    } 

$scope.comments = [ 
{username: 'Diana', contents:'In either a quantum world or in a higher dimension, the past, present and future co-exist!', upvotes: 5, downvotes:0}, 
{username: 'Cindy', contents:'Never wash strawberries or any berry unless you intend to eat them right away or they will mold.', upvotes: 7, downvotes:0} 
]; 
}]); 

Комментарии, приведенные выше, должны появиться .. Но они не .. Почему ??

+0

Любые ошибки в вашей командной строке терминала/командной строки? –

+0

Было бы проще сузить проблему, если вы предоставите какую-то меньшую версию кода, которая имеет те же проблемы, удалив некоторые из методов, которые не требуются для воспроизведения проблемы. –

+0

@Jezzabeanz Нет erroes .. он отлично работает – nj2237

ответ

0

Ошибка состояла в том, что я должен был добавить

<ui-view></ui-view> 

где я нуждался в мой шаблон для загрузки в соответствии с синтаксисом UI-маршрутизатора.

1

Я думаю, ваша проблема в том, что вы создали шаблон, но вы не используете шаблон.

Я не 100% уверен, что вам нужен шаблон, но попробовать:

<div ng-include src="home.html"></div> 

Смотрите этот пример переключения шаблонов динамически JSFiddle

+0

Да, я пробовал это, но он все еще ничего не отображает :( – nj2237

+0

Исправлено. Ваше решение подходит для ng-маршрута. , ui-router должен иметь , где мне нужен шаблон для визуализации.Спасибо :) – nj2237

+0

@learning Я рад, что вы это поняли! –

1

Похоже, что контроллер не будет ждать comment для загрузки из-за это не зависит от него. Задание контроллера зависит от обещания comment, а также сервис comments должен сделать зависимость прозрачной для углового.

app.controller('Base',[ 
'$scope','comments', 'comment', function($scope,comments,_comment){ 
    // ... 
}]);