【问题标题】:Filtering not working in transcluded DOM content过滤在嵌入的 DOM 内容中不起作用
【发布时间】:2017-10-27 19:25:26
【问题描述】:

我正在构建两个 AngularJS(1.6.5 版)组件,但在使用嵌入时无法进行过滤。

第一个组件是一个简单的容器,它使用嵌入来填充<div> 内容:

app.component('panelWithTitle', {
  template: '<div><h1>{{$ctrl.title}}</h1><div class="content" ng-transclude></div></div>',
  bindings: {
    title: '@'
  },
  require: 'title',
  transclude: true
});

第二个组件使用容器 (&lt;panel-with-title&gt;) 并为其提供一个简单的过滤(来自输​​入字段)列表:

app.component('mainComponent', {
  controller: function($scope) {
    $scope.allItems = ["10", "100", "200", "42", "1337"];
    // Simple filter function (may be more complicated)
    $scope.filterFunc = function (item) {
      if (!$scope.filterValue) {
        // No value
        return true;
      }
      return item.indexOf($scope.filterValue) !== -1;
    };
  },
  template: '<panel-with-title title="MyTitle">'            // Replace by <div>
      + '<input type="text" ng-model="filterValue">'
      + '<ul><li ng-repeat="item in allItems | filter:filterFunc">{{item}}</li></ul>'
      + '</panel-with-title>'                               // Replace by </div>
});

在该状态下,过滤不起作用,因为 $scope.filterValue 未定义。 Here is a demo Plunkr。我注意到:

  • 如果我不使用嵌入(例如:如果我用简单的 &lt;div&gt; 标记替换 &lt;panel-with-title&gt; 标记),过滤就会起作用。
  • 无论如何,$scope.allItems 的定义是正确的。

我做错了什么让它无法正常工作?为什么$scope.filterValue 未定义而$scope.allItems 已定义?

谢谢。

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-ng-repeat angularjs-ng-transclude


    【解决方案1】:

    您的$scope.filterValue 总是undefined 和过滤器返回true,因为您的模板使用不同的范围。

    所以添加$rootfilterValue 喜欢:

    <input type="text" ng-model="$root.filterValue">
    

    并在组件中使用$scope.$parent.filterValue:

    return item.indexOf($scope.$parent.filterValue) !== -1;
    

    Demo Plunker


    顺便说一句,好问题:)

    【讨论】:

    • 谢谢。这是工作。 :) 但是图表可能在这里有用。为什么我需要为filterValue 而不是allItems 这样做(如果我在过滤函数中使用它就很好定义)?
    【解决方案2】:

    如果你不想写更多的代码意味着(filterFunc函数)那么

    您应该将此代码连接到模型 (ng-model="filterValue"),以便通过模型直接过滤。 请在下面找到我的 plunker 链接 -

    http://plnkr.co/edit/sp9XFUMXLdmSwESujMQD?p=preview

    app.component('mainComponent', {
      controller: function($scope) {
        $scope.allItems = ["10", "100", "200", "42", "1337"];
      },
      template: '<panel-with-title title="MyTitle">'            // Replace by <div>
          + '<input type="text" ng-model="filterValue">'
          + '<ul><li ng-repeat="item in allItems | filter:filterValue">{{item}}</li></ul>'
          + '</panel-with-title>'                               // Replace by </div>
    });
    

    【讨论】:

    • 我知道。实际上这就是我添加“简单过滤功能(可能更复杂)”评论的原因。我真正的过滤功能并没有这么简单。 :) 无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    相关资源
    最近更新 更多