如何在ng-model上使用angularJs过滤器

时间:2015-07-09 12:58:54

标签: json angularjs angularjs-ng-repeat

我的json如下所示

  var content = [{
  "DocList": [
   {
  "Events": [
    {
      "CategoryName": "PressStatements",
      "DisplayName": "Press Statements",
      "ID": 9
    },
    {
      "CategoryName": "Reports",
      "DisplayName": "Reports",
      "ID": 10
    }
  ],
  "Heading": "News 2",
  "PageID": 23,
   "Date": "\/Date(1454537792000)\/"

},
{
  "Events": [
    {
      "CategoryName": "Research",
      "DisplayName": "Research",
      "ID": 6
    }
  ],
  "Heading": "Heading",
  "PageID": 20,
  "Date": "\/Date(1437417792000)\/"
}
]}
];


$scope.data=content;

 $scope.filterItems = function(g) {
//console.log('filterItems is run');
var ret = $filter('filter')(g.NewsList,"");
//g.filteredItemCount = ret.length
return ret
 };

 $scope.abms = [];


 //Options Inside Select tag
angular.forEach(news[0].NewsList, function(newsItems, index) {
  angular.forEach(newsItems.CategoryList, function(category, index){
    $scope.abms.push(category.DisplayName);
  });
});

我在选择选项中显示事件,具体取决于我必须显示数据,选择我正在使用带有ng-model的选择标记

<select ng-model="selected"><option ng-repeat="item1 in abms" >{{item1}}</option></select>
   <div id="dataRow{{$index}}" ng-repeat="item1 in (filtered = filterItems(d)) | findobj:selected">

  //display data depending on option selection

  </div>

如果我从Events [0]中选择任何categoryName,那么它应该显示来自DocList [0]数据的数据,并且对于select选项显示相同的数据。

//过滤器 - 不要这样做

myapp.filter('findobj', function() {
  return function(dataobj, selected) {
  return dataobj.filter(function(news) {
  //alert('got something');
    return (selected || []).some(function(s) {
    alert('got something');
    return news.CategoryList.CategoryName === s.CategoryList.CategoryName;
    });
   });
 };
});

如何实现?

提前致谢...

1 个答案:

答案 0 :(得分:1)

您需要修复此类findobj过滤器

myapp.filter('findobj', function () {
    return function (dataobj, selected) {
        if (!selected) return dataobj;//if nothing selected - return initial array
        return dataobj.filter(function (news) {
            //select only news where in category list places selected category
            return news.CategoryList.some(function (category) {
                //check display category name
                return category.DisplayName === selected;
            });
        });
    };
});

JSFIDDLE

上的工作示例