我有以下内容来显示图像列表(使用Angular):
var application = angular.module('Application', []);
application.controller('ImageController', function ImageController($scope, $http) {
$http.get('api/images').
success(function (data, status, headers, config) {
$scope.images = data;
}).
error(function (data, status, headers, config) {
});
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
<div class="overlay">
<a href="#">VOTE</a>
<span>{{image.Votes}}</span>
<a href="#">LOCK</a>
</div>
</div>
</div>
图像按预期显示,但我想:
- 点击链接投票
- 时调用"api/vote/{{image.id}}";
- 单击链接 LOCK 时调用 "api/lock/{{image.id}}";
我想两个链接都应该在一个表单内?不?
我该怎么做?有人可以帮助我吗?
更新
按照迪特的建议,我尝试了以下方法:
<div class="overlay">
<a ng-click="vote(image)" href="#">VOTE</a>
<span>{{image.Votes}}</span>
</div>
$scope.vote = function (image) {
$http.post('api/images/' + image.Id + '/vote', { id: image.Id }).
success(function (data, status, headers, config) {
alert("success");
}).
error(function (data, status, headers, config) {
alert(data);
alert(status);
});
};
有了这个,我得到了一个不好的请求...如果我尝试:
$http.post('api/images/2/vote', { id: image.Id }).
然后它工作...
我检查并成像。Id 等于 2。知道为什么它不起作用吗?
我不确定如何使用参数创建路径。
将 ng 单击添加到您的链接中
<div class="overlay">
<a ng-click="vote(image)" href="#">VOTE</a>
<span>{{image.Votes}}</span>
<a ng-click="lock(image)" href="#">LOCK</a>
</div>
然后在控制器中,您可以在单击函数中添加所需的 API 调用
application.controller('ImageController', function ImageController($scope, $http) {
$scope.vote = function (image) {
// image.id is available here
};
$scope.lock = function (image) {
// image.id is available here
};
$http.get('api/images').
success(function (data, status, headers, config) {
$scope.images = data;
}).
error(function (data, status, headers, config) {
});
});
还要尽量避免控制器内的 http' 调用。使用 Angular 服务进行抽象。并查看约翰爸爸的风格指南,不能推荐这个!