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
請詳細說明 「似乎並不合作。」 – kapa
我已經添加了我在控制檯中得到的錯誤...請檢查它 – Sam
「似乎不工作」意味着用戶輸入不會添加到posts數組。我希望將輸入添加到posts數組中,稍後在網頁中顯示數組元素 – Sam