获得AngularJS中的选定选项

时间:2014-03-24 06:18:19

标签: javascript angularjs twitter-bootstrap angularjs-ng-repeat angular-ui-bootstrap

我正在生成照片的缩略图列表(使用ng-repeat),在这些照片的每张照片下,我有两个按钮,一个用于查看更多详细信息,另一个用于购买。

我发现了如何映射按钮的问题。基本上我想要当用户点击照片A下面的购买按钮时,在预订表格中(这是一个不同的视图),他/她将看到有关照片A的详细信息,而不是让用户再次从照片A中选择照片一些下降。照片列表来自JSON字符串。

主要是我发现的难点是如何将点击了哪个按钮的详细信息传递给预订视图,以便我能够立即显示所选照片的​​详细信息。

我是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>

Angular JS:

App 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;
}]);

2 个答案:

答案 0 :(得分:2)

使用ngClick指令是一个好主意,因为@Ashesh建议

假设包含照片的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>

此外,您可以将此逻辑分解为例如一个photoService,以便您的控制器不会包含业务逻辑,因为您可以更容易地通过测试覆盖控制器和服务,因为您可以将它们分离。希望这会有所帮助。

答案 1 :(得分:1)

使用ngClick

<p><button type="button" class="btn btn-default" ng-click="photo.showPhotographer()">Photographer</button><br ><button type="button" class="btn btn-default" ng-click="photo.buy()">Purchase</button></p>

当然,photo.showPhotographer()等可以做你喜欢的事情:

function Photo() { // the photo object
    this.buy() {
        // api call to buy with the id of the photo or window.navigate('buy_url?id=' + this.id), etc.
    }
}