【问题标题】:When using Angular 1.6 ng-switch displaying key and value in filter list使用 Angular 1.6 ng-switch 在过滤器列表中显示键和值时
【发布时间】:2017-06-30 16:20:13
【问题描述】:

我正在尝试为产品列表创建条件过滤器,它工作正常,直到我更改产品模型以允许多个类别。一旦发生这种情况,过滤器就会损坏并显示出来
Broken Filter

这是产品的json结构示例

       {
        "title": "Product 2",
        "designer": "Designer 1",
        "id": "314",
        "category": [{
          "name": "Cat 5",
          "name": "Cat 3",

        }],
        "collection": "Collection 2",
        "type": "Type 2",
      },

这是过滤器的控制器

myApp.controller('myCtrl', function ($scope, Products) {
$scope.data = Products;
$scope.filter = {};
$scope.categories = ['category','type','collection','designer'];

$scope.addProps = function(obj, array) {
  if (typeof array === 'undefined') {
    return false;
  }
  return array.reduce(function (prev, item) {
    if (typeof item[obj] === 'undefined') {
      return prev;
    }
    return prev + parseFloat(item[obj]);
  }, 0);
}

$scope.getItems = function (obj, array) {
  return (array || []).map(function (w) {
    return w[obj];
  }).filter(function (w, idx, arr) {
    if (typeof w === 'undefined') {
      return false;
    }
    return arr.indexOf(w) === idx;
  });
};
// matching with AND operator
$scope.filterByPropertiesMatchingAND = function (data) {
  var matchesAND = true;
  for (var obj in $scope.filter) {
    if( $scope.filter.hasOwnProperty(obj) ) {
      if (noSubFilter($scope.filter[obj])) continue;
      if (!$scope.filter[obj][data[obj]]) {
        matchesAND = false;
        break;
      }
    }
  }
  return matchesAND;
};
// matching with OR operator
$scope.filterByPropertiesMatchingOR = function (data) {
  var matchesOR = true;
  for (var obj in $scope.filter) {
    if( $scope.filter.hasOwnProperty(obj) ) {
      if (noSubFilter($scope.filter[obj])) continue;
      if (!$scope.filter[obj][data[obj]]) {
        matchesOR = false;
      } else {
       matchesOR = true;
        break;
      }
     }
   }
  return matchesOR;
 };

如何仅访问类别的值,然后仅显示唯一类别?这是fiddle 的链接,在过去的2 个小时里,我试图让这段代码在js fiddle 上运行,但无济于事。

编辑

更新了小提琴http://jsfiddle.net/48qLjg2z/7/ 1.lint json文件

【问题讨论】:

    标签: javascript angularjs angular-controller


    【解决方案1】:

    你的小提琴有问题。尝试创建一个新的小提琴

    我创建了new one,它显示了一个不同的错误(产品未定义)。

     var products = product_list
    

    注意:我使用的是 Angular 1.5

    【讨论】:

      【解决方案2】:

      我猜是Cat 3之后的逗号,这里:

      "category": [{
        "name": "Cat 5",
        "name": "Cat 3",
      
      }],
      

      “JavaScript 从一开始就允许在数组字面量中使用尾随逗号……然而,JSON 不允许尾随逗号。”

      来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas


      编辑: 就像资源一样,您始终可以在此处验证 JSON:https://jsonlint.com/

      【讨论】:

      • 谢谢我用正确的 json 更新了小提琴
      • 你有同样的问题吗?
      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 2016-04-21
      相关资源
      最近更新 更多