In this recipe, we isolate the code for the filters from previous recipe in its own component: search_job
in the folder libcomponent
. You can follow along with the code in the project angular_view
.
The change we make in this recipe is transparent to the user; the web page stays the same, but the project code is refactored.
angular-view.html
, the <div id="filters">
section is now replaced by the HTML code for the component. Have a look at the following code:<search-job type-filter="ctrl.typeFilter" company-filter-map="ctrl.companyFilterMap"> </search-job>
JobListingController
, the following code is added:for (var company in companies) { companyFilterMap[company] = false; }
search_job_component.dart
as follows:import 'package:angular/angular.dart'; @Component( selector: 'search-job', templateUrl: 'packages/angular_view/component/search_job_component.html', publishAs: 'cmp') class SearchJobComponent { Map<String, bool> _companyFilterMap; List<String> _companies; @NgTwoWay('type-filter') String typeFilter = ""; @NgTwoWay('company-filter-map') Map<String, bool> get companyFilterMap => _companyFilterMap; void set companyFilterMap(values) { _companyFilterMap = values; _companies = companyFilterMap.keys.toList(); } List<String> get companies => _companies; void clearFilters() { _companyFilterMap.keys.forEach((f) => _companyFilterMap[f] = false); typeFilter = ""; } }
search_job_component.html
as follows:<div id="filters"> <div> <label for="type-filter">Filter jobs by type</label> <input id="type-filter" type="text" ng-model="cmp.typeFilter" value=" "> </div> <div> Filter jobs by company: <span ng-repeat="company in cmp.companies"> <label> <input type="checkbox" ng-model="cmp.companyFilterMap[company]">{{company}} </label> </span> </div> <input type="button" value="Clear Filters" ng-click="cmp.clearFilters()"> </div>
In step 1, we see that the main web page is now greatly simplified; instead of containing all of the markup to set up the search and filter views, it now just contains the reference to the component search_job
. This component has two attributes, whose values must be set by ctrl
, our JobListingController
. Step 2 shows the code to set companyFilterMap
. The two filter attributes are declared in step 3 as @NgTwoWay
. Indeed the user must be able to set them, and we want to be able to clear them in code in clearFilters()
. The component template code in step 4 is not changed.