javascript - AngularJS 两个组件之间的过滤器

标签 javascript angularjs binding components angularjs-filter

我知道我可以这样过滤:

<input type="search" ng-model="searchTable">
<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in $ctrl.rows | filter: searchTable">
      <td>{{ row.firstName }}</td>
      <td>{{ row.lastName }}</td>
    </tr>
  </tbody>
</table>

如果<input type="search" ng-model="searchTable">,我该如何过滤和<tr ng-repeat="row in $ctrl.rows | filter: searchTable">位于单独的组件中?

这是一个简单的 fiddle

据我了解,我需要添加 $onChanges()和表达式绑定(bind) bindings: { onChange: '&' }searchComponent ,但不完全理解如何实现。

谢谢

最佳答案

Here是工作 fiddle 。您将搜索词存储在父组件中并将其传递给两个子组件。

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

app.controller('appController', function() {
	this.search = "";
});

app.component('searchComponent', {
	template: `
  	<h4>{{ $ctrl.title }}</h4>
    <label>Search table</label>
    <input type="search" ng-model="$ctrl.search">
  `,
  controller: function() {
  	this.title = 'Search Component';
  },
  bindings: {
  	search: "="
  }
});

app.component('tableComponent', {
	template: `
  	<h4>{{ $ctrl.title }}</h4>
    <!-- <p>This works</p> 
    <label>Search table</label>
    <input type="search" ng-model="searchTable"> -->
    <table>
    	<thead>
      	<tr>
        	<th>First Name</th>
          <th>Last Name</th>
        </tr>
      </thead>
    	<tbody>
      	<tr ng-repeat="row in $ctrl.rows | filter: $ctrl.search">
        	<td>{{ row.firstName }}</td>
          <td>{{ row.lastName }}</td>
        </tr>
      </tbody>
    </table>
  `,
  controller: function() {
 		this.title = 'Table Component';
    
    this.rows = [
    	{firstName: 'Zulu', lastName: 'Apple'},
      {firstName: 'Alice', lastName: 'xRay'},
      {firstName: 'Fred', lastName: 'Rogers'}
    ];
  },
  bindings: {
  	search: "<"
  }
});
body {
  font-family: 'Arial', sans-serif;
}
table {
  border-collapse: collapse;
}
td, th {
  border: 1px solid grey;
  padding: 5px;
}
label {
  display: block;
}
input {
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="appController">
    <h3>Filter Between Components</h3>
    <search-component search="search"></search-component>
    <table-component search="search"></table-component>
  </div>
</div>

关于javascript - AngularJS 两个组件之间的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50604608/

相关文章:

javascript - 在javascript中进行文本搜索?

javascript - 为什么我的 &lt;script&gt; 标签不执行其中的代码?

angularjs - 使用 Angular Mocks 测试 Angular : Provider '$$sanitizeUri' must define $get factory method

javascript - 如何在 ag-grid cellEditor 组件内渲染 Angular Directive(指令)?

java - 为什么在绑定(bind)中调用绑定(bind)值的 get 会引发 stackoverflow 错误

c# - 使用 x :Static 向 xaml 中的数组添加值

javascript - 如何访问 Polymer 中根元素的文本?

javascript - 如何在 JavaScript 字符串中插入变量?

javascript - angularJS json获取资源?

wpf - 将行为绑定(bind)附加到 controltemplate 中的元素