【问题标题】:how to filter data with directive?如何使用指令过滤数据?
【发布时间】:2015-08-11 03:52:28
【问题描述】:

我正在尝试使用指令作为我的数据的过滤器。这是我的数据数组:

$scope.data = [{
          "id": 1,
          "name": "een"
        }, {
          "id": 2,
          "name": "twee"
}];

这是我作为选择实现的指令过滤器:

.directive('myFilter', function() {
      return {
        restrict: 'E',
        templateUrl: 'my-dialog.html',
        link: function($scope, $element, $attributes) {
          var testing = $scope.data | {
            filter: $element.choice
          };
          console.log($element.choice);
          console.log($attributes.choice);
          console.log($scope.choice);
          console.log(testing);
        }
      };
});

和模板网址:

<select name="" id="" ng-model='choice'>
  <option value=1>1</option>
  <option value=2>2</option>
</select>

这是定义指令的html:

<my-filter dt="data"></my-filter>

plunkr:http://plnkr.co/edit/zqS5HyH3AqaMVtEv107p?p=preview

如何更改指令,以便当我在组合中选择 1 时,数据被过滤为仅 1 记录 id=1 的记录?

更新:当我更改组合上的值时,我稍微更改了代码以尝试过滤 $scope.data:

  link: function($scope) {
            $scope.$watch('choice', function() {
                 var testing = $filter('filter')($scope.data,$scope.choice);
                 console.log(testing);
            });
          }

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    首先,您需要修复过滤器。这是右过滤器的示例:

    var myRedObjects = $filter('filter')(myObjects, { color: "red" });
    

    您可以在此处阅读有关在指令/控制器中使用过滤器的更多信息:Using Angular Filters inside the controller

    其次,你必须使用$scope.choice而不是$element.choice

    【讨论】:

    • 我稍微更改了代码,但仍然无法正常工作
    • 请检查此版本:plnkr.co/edit/yjTM5iA6wNLfce75Wvg7?p=preview 并打开调试控制台以查看 console.log
    • 你也可以将它与lambda表达式一起使用var myRedObjects = $filter('filter')(myObjects, (a=&gt;a.color=='red'));
    猜你喜欢
    • 2016-03-07
    • 2015-07-13
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多