簡體   English   中英

如何根據用戶從下拉列表中的選擇訪問數組元素的其他字段,以及如何使用 javascript 刪除重復項

[英]How to access other fields of array elements based on user selection from dropdown list and also how to remove the duplicates using javascript

以下是主 html 文件中的部分代碼

<select ng-model="UserSelected">
  <option value="" selected disabled>--Product--</option>
  <option ng-repeat="Product in proservice">{{Product.type}}</option>
</select>{{UserSelected}}

下面是帶有數組的 AngularJS 代碼,這里有一系列類型的產品,例如機器人、移動設備、電視等。我想根據用戶選擇的類型獲取數組行。

app.service('myService', function () {
  this.setProduct = function () {
    this.Products = [
        {id: 1, images: 'D:/angular/shop/src/home/robot3.jpg', Names: "ASIMO ", Price: "$1000", detail: "hello",type:"robot"},
        {id: 2,images: "D:/angular/shop/src/home/robot2.jfif", Names: "Bionic Hand", Price: "$2000", detail: "hi",type:"robot" },

        {id: 6, images: "D:/angular/shop/src/home/mobile3.png", Names: "Xiaomi", Price: "$3000", detail: "heyyy",type:"mobile" },
        {id: 7, images: 'D:/angular/shop/src/home/mobile4.jpg', Names: "oppo", Price: "$1000", detail: "hello",type:"mobile" },
        {id: 8, images: "D:/angular/shop/src/home/laptop1.jpg", Names: "Dell", Price: "$2000", detail: "hi",type:"laptop" },
        {id: 10, images: "D:/angular/shop/src/home/laptop2.jpg", Names: "Lenovo", Price: "$3000", detail: "heyyy",type:"laptop" },
        {id: 11, images: 'D:/angular/shop/src/home/laptop3.jpg', Names: "IBM", Price: "$1000", detail: "hello",type:"laptop" }] 
    return this.Products;
  };
  this.getProduct= function(){
    return this.Products;
  }
});

app.controller('HomeController', ['$scope', '$window','myService', function ($scope, $window, myService) {
  $scope.proservice = myService.setProduct();
}]);

如果要訪問用戶選擇,則需要在<option>標簽上添加value attr。 之后,您需要在ng-model="UserSelected"附近添加ng-change="onProductSelect()" ng-model="UserSelected" ,之后您將能夠跟蹤<select>元素上的更改。

例子:

<select ng-model="selectedProduct" ng-change="onProductSelect()">
  <option value="" selected disabled>--Product--</option>
  <option ng-repeat="product in products" value="{{ product.type }}">{{ product.type }}</option>
</select>

app.controller('HomeController', ['$scope', '$window','myService', function ($scope, $window, myService) {
  $scope.selectedProduct = '';
  $scope.products = myService.getProducts();

  $scope.onProductSelect = () => {
    $scope.products = $scope.products.filter(product => product.type === $scope.selectedProduct);
  };
}]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM