如何使用filter和orderby与isolated指令?

时间:2015-08-03 10:42:14

标签: angularjs filter directive

我使用隔离范围创建一个自定义指令,并且也在该指令中获取数据,但现在我的过滤器和orderby不在这里工作是我的指令:

def show
   @items = Item.where(category_id: @category.id, title: params[:tags]).order("created_at DESC")
end

控制器:

    <div my-data remoteurl='url' filter='test'>
    </div>

})();

DataTable.html

 (function() {

 'use strict';

   var myApp = angular.module('myApp', [])
    .controller('myAppCtrl', ['$scope', '$http', function($scope, $http) {
  $scope.url = 'https://www.reddit.com/r/worldnews/new.json';
  $scope.filter= 'test';
  $scope.orderBy= 'sortExpression';
}])
.directive('myData', ['$http', function($http) {
  return {
    restrict: 'A',
    scope: {
      remoteurl: '=',
      filter: '=',
      orderBy: '='
     // orderBy:'sortExpression':'order' ;
    },
    templateUrl: 'DataTable.html',
    link: function(scope, element, attr) {

      $http.get(scope.remoteurl)
        .success(function(response) {
          scope.names = response.data.children;
        });
    }
  };
}]);

 我正在传递所有参数,但只有url正在运行过滤器并且orderby不起作用,任何人都可以纠正我吗?

1 个答案:

答案 0 :(得分:2)

它与隔离范围无关。通常,您以正确的方式传递变量 - 从控制器通过= - 符号传递给指令。

您忘记将orderBy传递给指令,以及了解过滤器和orderBy通常如何工作。请查看filterorderBy的文档,并查看示例。

更正了指令代码,现在将控制器的orderBy范围变量传递给指令。

<div my-data remoteurl='url' filter='test' order-by="orderBy">
</div>

正如我已经评论过的,您的表行代码应如下所示:

<tr ng-repeat="x in names | filter:filter | orderBy:orderBy">

在控制器中,我设置了以下过滤器和orderBy字符串。

$scope.filter= 'obama';
$scope.orderBy= '-data.score'; //the "-" stands for reverse ordering

当您定义类似此filter:test的过滤器时,过滤器基于名为test的范围变量,例如$scope.test。在您的范围内,过滤器位于范围变量$scope.filter内,因此过滤器的正确调用为filter:filter

我在这里设置了一个有效的plnkr:http://plnkr.co/edit/FGZVaPrvbUcdvNRnKMk4?p=preview