2016-01-13 50 views
0

我正在尝试编写用于发布用户评论的角码,我想从控制器中将名为帖子的数组推入工厂。我写了一些代码,它似乎不工作。请花些时间在这里纠正我的代码!插入用户输入到角厂

在这里不用我的index.html

<body ng-app="flapperNews" ng-controller="MainCtrl" class="col-sm-4"> 
<div ng-repeat="post in posts | orderBy:'-upvotes'" class="well "> 
    <span > 
     <span ng-click="incrementUpvotes(post)" class="btn btn-primary">+</span> 
     <span ng-click="decrementUpvotes(post)" class="btn btn-danger">-</span> 
     {{post.title}} - upvotes: <span class="label label-success">{{post.upvotes}}</span><br> 
    </span> 
</div> 

<div> 
    <div><h3 class="text-warning">Add new Post</h3></div> 
    <form ng-submit="addPost()"> 
     <input type="text" ng-model="title" class="form-control"> 
     <button type="submit" class="btn btn-success">Post</button> 
    </form> 
</div> 
</body> 

这里是我的app.js

var app = angular.module('flapperNews', []); 

app.factory('newposts',[function(){ 
    var o = { 
     posts: [] 
    }; 
    return o; 
}]); 

app.controller('MainCtrl',['newposts',function($scope,newposts){ 
    $scope.posts = newposts.posts; 
    $scope.addPost = function(){ 
     if(!$scope.title || $scope.title === '') { return; } 
     $scope.posts.push({title: $scope.title, upvotes: 0}); 
     $scope.title=''; 
    }; 
    $scope.incrementUpvotes = function(post) { 
     post.upvotes += 1; 
    }; 
    $scope.decrementUpvotes = function(post) { 
     post.upvotes -= 1; 
    }; 
}]); 

,我在控制台得到的错误是

TypeError: Cannot read property 'post' of undefined 
at new <anonymous> (app.js:11) 
at d (angular.min.js:35) 
at Object.instantiate (angular.min.js:35) 
at angular.min.js:67 
at angular.min.js:54 
at r (angular.min.js:7) 
at N (angular.min.js:53) 
at g (angular.min.js:47) 
at angular.min.js:46 
at angular.min.js:18 
+0

请详细说明 “似乎并不合作。” – kapa

+0

我已经添加了我在控制台中得到的错误...请检查它 – Sam

+0

“似乎不工作”意味着用户输入不会添加到posts数组。我希望将输入添加到posts数组中,稍后在网页中显示数组元素 – Sam

回答

0

而不是

app.controller('MainCtrl',['newposts',function($scope,newposts) { 

尝试

app.controller('MainCtrl',['$scope', 'newposts',function($scope,newposts) {