选择“对象”逻辑

时间:2013-10-16 09:53:24

标签: angularjs

我以前做过这件事,但我不能为我的生活记住这一点。我希望用户能够通过单击<li>中的按钮来选择产品,然后将其传递给数组。除此之外,<li>还需要有一个课程“活跃”。一旦该项目在选定的数组中:

<li class="row" data-ng-repeat="product in products">
  <div class="col-lg-9">
    <h3>{{product.name}}</h3>
    <p>{{product.description}}</p>
  </div>
  <div class="col-lg-3">
    <button class="btn btn-primary" data-ng-click="selectProduct(product.id)">Select Product</button>
  </div>
</li>

是HTML,这是控制器:

app.controller("MainController", function($scope, $http) {
  $scope.selected_products = []
  $scope.products = [
    {
      name: 'Example product',
      description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, assumenda, dolor, ipsa, atque obcaecati tempora perspiciatis earum vitae amet cum nostrum blanditiis ducimus culpa molestiae temporibus porro debitis voluptatibus libero.',
      category: 'VT'
    },
    {
      name: 'Example product 2',
      description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, assumenda, dolor, ipsa, atque obcaecati tempora perspiciatis earum vitae amet cum nostrum blanditiis ducimus culpa molestiae temporibus porro debitis voluptatibus libero.',
      category: 'VT'
    }
  ]

  $scope.selectProduct = function(name) {
    console.log(name)
  }
})

有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分:1)

你在这里:

 $scope.isSelected = function(product){
      return this.selected_products.indexOf(product)>-1;
  }

  $scope.selectProduct = function(product) {
      if(!this.isSelected(product)){
          this.selected_products.push(product);    
      }
  }

使用它像:

 <button ng-disabled="isSelected(product)" data-ng-click="selectProduct(product)">Select Product</button>

工作示例:http://plnkr.co/edit/sPAN36?p=preview