为什么自定义滤镜在角度js中不起作用?

时间:2016-04-30 07:22:06

标签: javascript angularjs angularjs-directive angularjs-scope

我需要使用ng-repeat显示已排序的数据。我从此示例中获取帮助

Order by Object key in ng-repeat

但添加了相同的钳工,但没有得到正确的输出。这不是我的清单。

这是我的代码 http://plnkr.co/edit/qFaBYnwCVTZJZSiw6hdD?p=preview

var app = angular.module('app', []);

app.controller('MyCtrl',function($scope){
   $scope.lines = {
     "a": {name:"bb"},
    "aa":{name: 'aa'},
    "zz": {name:"zz"},
    "oo":{name: 'oo'}, 
    "kk": {name:"k"},
    "j":{name: "a"},
    "n": {name:"n"},
    "c":{name: "c"}
}
})
app.filter('toArray', function() { return function(obj) {
    if (!(obj instanceof Object)) return obj;
    return _.map(obj, function(val, key) {
        return Object.defineProperty(val, '$key', {__proto__: null, value: key} );
    });
}});

1 个答案:

答案 0 :(得分:0)



var app = angular.module('app', []);

app.controller('MyCtrl',function($scope){
   $scope.lines = {
     "a": {name:"bb"},
    "aa":{name: 'aa'},
    "zz": {name:"zz"},
    "oo":{name: 'oo'}, 
    "kk": {name:"k"},
    "j":{name: "a"},
    "n": {name:"n"},
    "c":{name: "c"}
};
  
  $scope.myFilter = function(){
    var array=[];
    angular.forEach($scope.lines,function(value,key){
       array.push(value);
      });
    return array;
    
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
  <div ng-repeat="(key, line) in myFilter() | orderBy:'name'">
      <div class="preview">{{line.name}}</div>
   </div>
   </div>
&#13;
&#13;
&#13;

试试这个。你应该将object属性传递给orderBy。

   <div ng-repeat="(key, line) in lines | toArray | orderBy:'name'">

修改

你可以在控制器中使用过滤器。比如

  $scope.myFilter = function(){
   var array=[];
   angular.forEach($scope.lines,function(value,key){
   array.push(value);
  });
  return $filter('orderBy')(array, 'name');
 }

使用过滤器你应该注入服务过滤器。

  app.controller('MyCtrl',function($scope,$filter){