我正在生成照片的缩略图列表(使用 ng-repeat),在每一张照片下我都有两个按钮,一个用于查看更多详细信息,另一个用于购买。
我发现如何映射按钮有问题。基本上,我希望当用户在预订表单(这是不同的 View )中单击照片 A 下面的购买按钮时,他/她将看到与照片 A 相关的详细信息,而不是让用户再次选择照片有些掉下来。照片列表来自 JSON 字符串。
我发现的主要困难是如何将单击哪个按钮的详细信息传递到预订 View ,以便我能够立即显示所选照片的详细信息。
我是 AngularJS 的新手,不确定是否有一种简单的方法可以完成。
我的 HTML 是这样的:
<div class="col-md-4 ng-scope" ng-repeat="photo in photos">
<div class="thumbnail">
<img src="{{photo.thumbnail}}" alt="{{photo.title}}">
<div class="caption">
<h4 class="ng-binding">{{photo.title}}</h4>
<p><button type="button" class="btn btn-default">Photographer</button><br ><button type="button" class="btn btn-default">Purchase</button></p>
</div>
</div>
AngularJS:
应用程序JS
angular
.module('app', [
'ui.router'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('photos', {
url: '/photos',
templateUrl: 'templates/photos.html',
controller: 'photosCtrl',
resolve: { photos: ['$http', function($http){
return $http.get('api/photos.json').then(function(response){
return response.data;
});
}]}
})
}]);
photosCtrl JS:
angular
.module('app')
.controller('photosCtrl', ['$scope', 'photos', function($scope, photos) {
$scope.photos = photos;
}]);
最佳答案
正如 @Ashesh 建议的那样,使用 ngClick
指令是个好主意
假设包含照片的 JSON 附带一堆照片对象,我宁愿向 photosCtrl
范围添加两个函数,如下所示:
angular.module('app')
.controller('photosCtrl', ['$scope', 'photos', function($scope, photos) {
$scope.photos = photos;
$scope.showDetailsOf = function(photo) {
// photo argument is the actual object of which 'details' button was pressed
// coming from the ngRepeat in your template example
console.log('show details of ' + photo.title);
}
$scope.purchase = function(photo) {
// same as above
console.log('purchase ' + photo.title);
}
}]);
模板应如下所示:
<button type="button" class="btn btn-default" ng-click="showDetailsOf(photo)">Details</button>
<button type="button" class="btn btn-default" ng-click="purchase(photo)">Purchase</button>
此外,您可以将此逻辑分解为例如a photoService
,这样您的 Controller 就不会包含业务逻辑,这总是更可取的,因为您的 Controller 和服务都可以更容易地被测试覆盖,因为您将它们解耦。希望这会有所帮助。
关于javascript - 在 AngularJS 中获取选定的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602296/