//app.js
var blogApp = angular.module('BlogApp', []); //angular module setup, matches ng-app from index.html
blogApp.controller('BlogController', function($scope, $http){ //have to add $http if your going to use http (inject the dependancy)
$scope.createPost = createPost; //grabbing createPost from index.html (binding)
$scope.deletePost = deletePost; //map deletePost from index.html
function init(){ //put everything that happens when site first loads in init function, good practice
getAllPosts();
}
init(); //call init function to show all database posts
function getAllPosts(){ //retrieve latest blogposts
$http.get("/api/blogpost").success(function (posts){ //if its successfull, send posts back to client
$scope.posts = posts; //send back to client using $scope
});
}
function createPost(post){ //taking post object from ng-model in index.html
console.log(post); //displaying post information in console log on html site
$http.post("/api/blogpost", post).success(getAllPosts); //push 'post' data to api/blogpost url, also call function getAllPosts when posting new post
console.log(postId);
}
function deletePost(postId){ //deletePost is the same name as in index file for ng-click
console.log(postId);
$http.delete("/api/blogpost/"+postId).success(getAllPosts); //delete just one post with specific id, without + postId it would delete all posts
}
});
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="app.js"></script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea/>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<div ng-repeat="post in posts">
<h2>
{{post.title}}
<a ng-click="deletPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>
{{post.body}}
</p>
</div>
{{posts}}
</div>
</body>
</html>
由于某种原因,我的ng-click按钮未调用我的deletePost()函数。试图弄清楚这个问题已经花了几个小时,却不知道为什么它不起作用。单击字形图标时,绝对没有任何响应。尝试按钮以及仍然没有反应。有人看到我在做什么错吗?
最佳答案
由于拼写错误,它无法正常工作:
ng-click="deletPost(post._id)"
至
ng-click="deletePost(post._id)"