将用户输入插入角度工厂

时间:2016-01-13 09:31:17

标签: angularjs

我正在尝试编写用于发布用户评论的角度代码,我想将名为posts的数组从控制器推送到工厂。我写了一些代码,似乎没有用。请花点时间在这里纠正我的代码!

这里是我的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

1 个答案:

答案 0 :(得分:0)

而不是

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

尝试

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