【发布时间】: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
});
第二个组件使用容器 (<panel-with-title>) 并为其提供一个简单的过滤(来自输入字段)列表:
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。我注意到:
- 如果我不使用嵌入(例如:如果我用简单的
<div>标记替换<panel-with-title>标记),过滤就会起作用。 - 无论如何,
$scope.allItems的定义是正确的。
我做错了什么让它无法正常工作?为什么$scope.filterValue 未定义而$scope.allItems 已定义?
谢谢。
【问题讨论】:
标签: javascript angularjs angularjs-scope angularjs-ng-repeat angularjs-ng-transclude