我有一个 REST API,我可以从中接收数据,例如项目列表。有人告诉我 JavaScript 的美妙之处在于,当某些条件发生变化时,您不必重新加载整个页面。
我将 angular 连接到我的 API 来尝试一下。我现在遇到的问题是,在调用我的 API 删除一个项目后,整个列表(不是页面,页面不会刷新)被重新加载。我希望在我的页面上发生的唯一事情是我已删除的项目从屏幕上删除,而列表中的其他项目不会重新加载。我尝试了很多东西,但没有任何效果。这是我的一些代码。所以这就是我在屏幕上看到的。我删除了一个项目。整个列表消失了几毫秒然后重新出现,当然没有我删除的项目。
评论.html:
<h1>Reviews</h1>
<ul>
<li ng-repeat="review in reviews track by review.id">
<h3><a href="http://localhost:8080/videogamereviews/#!/show/{{review.id}}">{{review.title}}</a></h3>
<p>
{{ review.conclusie }}
</p>
<p><a href="http://localhost:8080/videogamereviews/#!/delete/{{review.id}}">delete this review</a>
</p>
<p><a href="http://localhost:8080/videogamereviews/#!/edit/{{review.id}}">edit this review</a>
</p>
</li>
</ul>
应用程序.js
var VideogameReviewsApp = angular.module('VideogameReviewsApp', ['ngRoute', 'ngResource']).config(
['$routeProvider', '$resourceProvider',
function($routeProvider, $resourceProvider) {
$routeProvider.when('/', {
controller: ReviewCtrlAll,
templateUrl: 'reviews.html'
}).when('/home', {
controller: Test,
templateUrl: 'reviews.html'
}).
when('/show/:id', {
controller: ReviewCtrl,
templateUrl: 'review.html'
}).when('/delete/:id', {
controller: DeleteCtrl,
templateUrl: 'reviews.html'
}).when('/new', {
controller: PostCtrl,
templateUrl: 'newreview.html'
}).when('/edit/:id', {
controller: EditCtrl,
templateUrl: 'newreview.html'
}).
otherwise({
redirectTo: '/'
});
$resourceProvider.defaults.stripTrailingSlashes = false;
}
]);
VideogameReviewsApp.factory('Review', function($resource) {
return $resource('http://localhost/videogamereviews/review/:id', {
id: '@id'
},
{
update: {
method: 'PUT'
}
});
});
var DeleteCtrl = function($scope, Review, $routeParams, $window, $location) {
Review.delete({
id: $routeParams.id
}, function() {
$scope.reviews = Review.query();
});
}
希望对新手程序员有所帮助!
您不需要重新加载页面,因为 Angular 为您提供了两种方式的绑定。因此,如果您从评论数组中删除一个项目(以编程方式),那么您的 UI 就会更新。
你的控制器应该是这样的
function homeController ($scope, $timeout) {
$scope.persons = [{
name : 'A',
age : 12
}, {
name : 'B',
age : 15
}]
$scope.remove = function (person, index) {
console.log(person)
console.log(index)
// faking api called
$timeout(function () {
// if your api called is succesfull
// then remove the person from the array
$scope.persons.splice(index, 1)
}, 500)
}
}
和你的 .html 文件
<ul>
<li ng-repeat="person in persons">
<span>{{person.name}}</span>
<button ng-click="remove(person, $index)">x</button>
</li>
</ul>
和现场演示链接,如果你想测试它
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句