AngularJS- Switching data sets based on filter -
i'm beginning explore angularjs. watched tutorial explaining how set basic filter. i'm attempting expand on concept. feel way i'm approaching inefficient.
the method used here requires new ctrl set each new data set. if had 5 different data sets wanted set filters for, require 5 different controllers. when @ example below, see lot of repeated code makes me thing can done differently.
here's working jsfiddle: http://jsfiddle.net/smithd/euz7q/1/
<div ng-app="searchapp"> <div ng-controller="filterctrl" class="filter"> <h1>search demo</h1> <hr/> <div ng-switch on="selection"> <!-- <div ng-switch-default>default</div> --> <div ng-switch-when="avengers"> <div ng-controller="avengersctrl"> <input type="text" ng-model="search"> <table ng-show="(filtereddata = (avengers.cast | filter:search)) && search && search.length >= 1"> <tr ng-repeat="actor in avengers.cast | filter:search"> <td>{{actor.name}}</td> <td>{{actor.character}}</td> </tr> </table> </div> </div> <div ng-switch-when="expendables"> <div ng-controller="expendablesctrl"> <input type="text" ng-model="search"> <table ng-show="(filtereddata = (expendables.cast | filter:search)) && search && search.length >= 1"> <tr ng-repeat="actor in expendables.cast | filter:search"> <td>{{actor.name}}</td> <td>{{actor.character}}</td> </tr> </table> </div> </div> <select ng-model="selection" ng-options="item item in items" class="filter"></select> </div> </div> </div>
here's example using 1 controller , storing data in service.
<div ng-controller="filterctrl"> <h1>search demo</h1> <hr/> <select ng-model="selection" ng-options="item item in items" class="filter"></select> <hr/> <div> <input type="text" ng-model="search"> <table ng-show="(filtereddata = (cast | filter:search)) && search && search.length >= 1"> <tr ng-repeat="actor in cast | filter:search"> <td>{{actor.name}}</td> <td>{{actor.character}}</td> </tr> </table> </div> </div>
var app = angular.module('plunker', []); app.factory('dataservice', function () { return { avengers: [...],expendables: [...]} }); app.controller('filterctrl', function($scope,dataservice){ $scope.items = ['avengers', 'expendables']; $scope.selection = $scope.items[0]; /* change data when select changes*/ $scope.$watch('selection',function(){ $scope.cast=dataservice[$scope.selection]; }) });
Comments
Post a Comment