2017-02-23 8 views
1

У меня есть рабочее поле поиска и набор флажков, которые правильно работают с моими данными внутри контроллера в Angular JS 1.5.5. У меня есть второй контроллер с полем поиска и некоторыми переключателями углового материала. Я хочу, чтобы переключатели привязывались к флажкам, но не знаю, как их связать с одним контроллером на другой, плюс переключатели являются true/false, но значения true/false для флажков не соответствуют true/false, они являются строками.Угловой материал md-switch и поиск входных сигналов в одном контроллере на другой контроллер

.controller('mainController', function($scope, $route, $routeParams, $location, $http) { 

      // Data object 
      $http({ 
       method: 'GET', 
       url: 'utahgolf.json' 
      }) 
      .success(function (data, status, headers, config) { 
       $scope.courses = data; 
      }) 
      .error(function (data, status, headers, config) { 
       // something went wrong :(
      }); 
    // Filter defaults 
    $scope.Filter = new Object(); 
    $scope.Filter.courseType = { 
           'public':'public', 
           'private':'private', 
           'military': 'military', 
           'resort': 'resort' 
         }; 
    $scope.Filter.region = { 
           'northern':'northern', 
           'central':'central', 
           'southwestern': 'southwestern', 
           'southeastern': 'southeastern' 
         }; 
    // Default order 
    $scope.OrderFilter = 'name'; 
}) 

// Global search filter 
.filter('searchFilter',function($filter) { 
     return function(items,searchfilter) { 
       var isSearchFilterEmpty = true; 
       angular.forEach(searchfilter, function(searchstring) { 
        if(searchstring !=null && searchstring !=""){ 
         isSearchFilterEmpty= false; 
        } 
       }); 
     if(!isSearchFilterEmpty){ 
       var result = []; 
       angular.forEach(items, function(item) { 
        var isFound = false; 
         angular.forEach(item, function(term,key) { 
          if(term != null && !isFound){ 
           term = term.toString(); 
           term = term.toLowerCase(); 
           angular.forEach(searchfilter, function(searchstring) { 
            searchstring = searchstring.toLowerCase(); 
            if(searchstring !="" && term.indexOf(searchstring) !=-1 && !isFound){ 
             result.push(item); 
             isFound = true; 
            } 
           }); 
          } 
          }); 
         }); 
      return result; 
     }else{ 
     return items; 
     } 
    } 
}) 

.factory('ser1', function(){ 

       courses = { 
        public: true, 
        private: true, 
        military: true, 
        resort: true, 
       }; 
     return courses; 

}) 

.controller('one', function($scope, ser1){ 
     $scope.courses = ser1; 
}) 


.controller('two',function($scope, ser1){ 
     $scope.courses = ser1; 
     //console.log($scope.courses); 
}) 

.controller('SwitchDemoCtrl', function($scope, ser1) { 

     $scope.data = ser1; 


    $scope.check = function() { 
      //console.log($scope.data); 
     } 


    $scope.message = 'false'; 

    $scope.change = function(cbState) { 
    $scope.message = cbState; 
     //console.log($scope.message); 

    }; 
}) 

HTML-поиск Страницы:

<div class="inbox" ng-controller="mainController"> 

      <!-- <div layout="row" layout-align="center center" class="bar"> 
       <input type="text" class="search" ng-model="data.searchString" placeholder="Enter search terms" /> 
       <i class="material-icons search-info" ng-click="showAlert($event)">info</i> 
      </div> --> 

      <label>Search: <input ng-model="searchText"></label> 
       <h2>Course Type</h2> 
       <label>Public</label> 
       <input type="checkbox" ng-model="Filter.courseType.public" ng-true-value="'public'" ng-false-value="'!public'" />&nbsp; 
       <label>Private</label> 
       <input type="checkbox" ng-model="Filter.courseType.private" ng-true-value="'private'" ng-false-value="'!private'" />&nbsp; 
       <label>Military</label> 
       <input type="checkbox" ng-model="Filter.courseType.military" ng-true-value="'military'" ng-false-value="'!military'" />&nbsp; 
       <label>Resort</label> 
       <input type="checkbox" ng-model="Filter.courseType.resort" ng-true-value="'resort'" ng-false-value="'!resort'" />&nbsp; 
       <hr /> 
       <h2>Region</h2> 
       <label>Northern</label> 
       <input type="checkbox" ng-model="Filter.region.northern" ng-true-value="'northern'" ng-false-value="'!northern'" />&nbsp; 
       <label>Central</label> 
       <input type="checkbox" ng-model="Filter.region.central" ng-true-value="'central'" ng-false-value="'!southern'" /> 
       <label>Southwestern</label> 
       <input type="checkbox" ng-model="Filter.region.southwestern" ng-true-value="'southwestern'" ng-false-value="'!southwestern'" /> 
       <label>Southeastern</label> 
       <input type="checkbox" ng-model="Filter.region.southeastern" ng-true-value="'southeastern'" ng-false-value="'!southeastern'" /> 
       <hr /> 
       <h2>Results:</h2> 


      <div ng-repeat="course in courses | filter:searchText | searchFilter:Filter.name | searchFilter:Filter.courseType | searchFilter:Filter.region | orderBy:OrderFilter" > 

      <div flex-xs="100" flex-gt-xs="100" layout="column"> 
        <md-card ng-click="cardSelected(course.id)" class="cardAsLink"> 
        <md-card-title> 
         <md-card-title-text class="md-card-title-text"> 
          <span class="md-headline courses-name">{{course.name}}</span> 
          <span class="md-subhead">{{course.city}}, {{course.state}}</span> 
          <span class="md-subhead">{{course.coursetype}} | {{course.holes}} Holes</span> 
          <!-- <span class="md-subhead">{{course.phone}}</span> --> 
         </md-card-title-text> 
         <md-card-title-media> 
          <div class="md-media-sm card-media"><img class="img img-responsive courses-card-image" ng-src="img/thumbs/{{course.id}}-1.jpg"></div> 
         </md-card-title-media> 
        </md-card-title> 
        <!-- <md-card-actions layout="row" layout-align="center"> 
          <md-button><a href="#/course/{{course.id}}"><i class="material-icons tk-action-icon">pageview</i></a></md-button> 
          <md-button><a href="#/course/{{course.id}}"><i class="material-icons tk-action-icon">directions</i></a></md-button> 
          <md-button><i class="material-icons tk-action-icon">phone</i></md-button> 
        </md-card-actions> --> 
        </md-card> 
      </div> 
     </div> 
</div> 

материал выключатели Дизайна и второе окно поиска:

<div ng-controller='two'> 
    <div class="search-filter-module"> 
     Search:<br /> 
     <input type='search' class="search-filter" ng-model="searchText"/><a title="clear input" ng-show="searchText != null" class="clear clear-search" ng-click="searchText = null"><i ng-show="searchText != null" class="material-icons">clear</i></a> 
    </div> 
     Course Type: 
    <md-switch ng-model="courses.public" aria-label="Switch 1" ng-click="check()"> 
     Public 
    </md-switch> 
    <md-switch ng-model="courses.private[![enter image description here][1]][1]" aria-label="Switch 2" ng-click="check()"> 
     Private 
    </md-switch> 
    <md-switch ng-model="courses.military" aria-label="Switch 3" ng-click="check()"> 
     Military 
    </md-switch> 
    <md-switch ng-model="courses.resort" aria-label="Switch 4" ng-click="check()"> 
     Resort 
    </md-switch> 
    Region: 
    <md-switch ng-model="courses.northern" aria-label="Switch 5" ng-click="check()"> 
     Northern 
    </md-switch> 
    <md-switch ng-model="courses.central" aria-label="Switch 6" ng-click="check()"> 
     Central 
    </md-switch> 
    <md-switch ng-model="courses.southwestern" aria-label="Switch 7" ng-click="check()"> 
     Southwest 
    </md-switch> 
    <md-switch ng-model="courses.southeastern" aria-label="Switch 8" ng-click="check()"> 
     Southeast 
    </md-switch> 
</div> 

ответ

1

Для работы с угловым материалом, вы можете использовать ng-true-value и ng-false-value к установите объект фильтра.

Чтобы подключить два контроллера вместе, я рекомендую создать метод службы, который возвращает объект настроек фильтра. Затем вы можете ввести службу в оба контроллера и установить для нее переменную локальной области. В любое время один контроллер изменяет объект будет отражать в другой контроллер:

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

 
app.controller('mainController', function($scope, filterSettings) { 
 

 
    $scope.filter = filterSettings; // retrieve settings object from service method and bring into scope  
 
    $scope.OrderFilter = 'name'; // Default sort order 
 

 
    // Data object 
 
    $scope.courses = [{ 
 
    name: 'Course 1', 
 
    courseType: 'Public', 
 
    region: 'Northern' 
 
    }, { 
 
    name: 'Course 2', 
 
    courseType: 'Public', 
 
    region: 'Northern' 
 
    }, { 
 
    name: 'Course 3', 
 
    courseType: 'Private', 
 
    region: 'Northern' 
 
    }, { 
 
    name: 'Links 4', 
 
    courseType: 'Private', 
 
    region: 'Northern' 
 
    }, { 
 
    name: 'Links 5', 
 
    courseType: 'Private', 
 
    region: 'Northern' 
 
    }, { 
 
    name: 'Links 6', 
 
    courseType: 'Public', 
 
    region: 'Southeastern' 
 
    }, { 
 
    name: 'Links 7', 
 
    courseType: 'Public', 
 
    region: 'Southeastern' 
 
    }, { 
 
    name: 'Links 8', 
 
    courseType: 'Military', 
 
    region: 'Southeastern' 
 
    }, { 
 
    name: 'Course 9', 
 
    courseType: 'Private', 
 
    region: 'Southeastern' 
 
    }, { 
 
    name: 'Course 10', 
 
    courseType: 'Private', 
 
    region: 'Southeastern' 
 
    }]; 
 
}); 
 

 
app.controller('secondController', function($scope, filterSettings) { 
 
    $scope.filter = filterSettings; // retrieve settings object from service method and bring into scope 
 
}); 
 

 
app.factory('filterSettings', function() { 
 

 
    // Filter defaults 
 
    var settings = {}; 
 
    settings.searchText = ''; 
 
    settings.courseType = { 
 
    'public': 'public', 
 
    'private': 'private', 
 
    'military': 'military', 
 
    'resort': 'resort' 
 
    }; 
 
    settings.region = { 
 
    'northern': 'northern', 
 
    'central': 'central', 
 
    'southwestern': 'southwestern', 
 
    'southeastern': 'southeastern' 
 
    }; 
 

 
    return settings; 
 
}); 
 

 
// Global search filter 
 
app.filter('searchFilter', function($filter) { 
 
    return function(items, searchfilter) { 
 
    var isSearchFilterEmpty = true; 
 
    angular.forEach(searchfilter, function(searchstring) { 
 
     if (searchstring != null && searchstring != "") { 
 
     isSearchFilterEmpty = false; 
 
     } 
 
    }); 
 
    if (!isSearchFilterEmpty) { 
 
     var result = []; 
 
     angular.forEach(items, function(item) { 
 
     var isFound = false; 
 
     angular.forEach(item, function(term, key) { 
 
      if (term != null && !isFound) { 
 
      term = term.toString(); 
 
      term = term.toLowerCase(); 
 
      angular.forEach(searchfilter, function(searchstring) { 
 
       searchstring = searchstring.toLowerCase(); 
 
       if (searchstring != "" && term.indexOf(searchstring) != -1 && !isFound) { 
 
       result.push(item); 
 
       isFound = true; 
 
       } 
 
      }); 
 
      } 
 
     }); 
 
     }); 
 
     return result; 
 
    } else { 
 
     return items; 
 
    } 
 
    } 
 
});
body { 
 
    font-family: calibri, arial; 
 
} 
 

 
h2 { 
 
    font-size: 14pt; 
 
    font-weight: bold; 
 
} 
 

 
li { 
 
    font-family: courier; 
 
} 
 

 
th { 
 
    font-weight: bold; 
 
    cursor: pointer; 
 
    text-align: left; 
 
}
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css"> 
 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.js"></script> 
 

 
<div ng-app="app" ng-cloak> 
 
    <section layout="row" flex=""> 
 
    <div ng-controller="mainController" style="margin: 0 20px;"> 
 
     <label>Search: 
 
     <input ng-model="filter.searchText"> 
 
     </label> 
 
     <h2>Course Type</h2> 
 
     <label>Public</label> 
 
     <input type="checkbox" ng-model="filter.courseType.public" ng-true-value="'public'" ng-false-value="'!public'" />&nbsp; 
 
     <label>Private</label> 
 
     <input type="checkbox" ng-model="filter.courseType.private" ng-true-value="'private'" ng-false-value="'!private'" />&nbsp; 
 
     <label>Military</label> 
 
     <input type="checkbox" ng-model="filter.courseType.military" ng-true-value="'military'" ng-false-value="'!military'" />&nbsp; 
 
     <label>Resort</label> 
 
     <input type="checkbox" ng-model="filter.courseType.resort" ng-true-value="'resort'" ng-false-value="'!resort'" />&nbsp; 
 
     <hr /> 
 
     <h2>Region</h2> 
 
     <label>Northern</label> 
 
     <input type="checkbox" ng-model="filter.region.northern" ng-true-value="'northern'" ng-false-value="'!northern'" />&nbsp; 
 
     <label>Central</label> 
 
     <input type="checkbox" ng-model="filter.region.central" ng-true-value="'central'" ng-false-value="'!southern'" /> 
 
     <label>Southwestern</label> 
 
     <input type="checkbox" ng-model="filter.region.southwestern" ng-true-value="'southwestern'" ng-false-value="'!southwestern'" /> 
 
     <label>Southeastern</label> 
 
     <input type="checkbox" ng-model="filter.region.southeastern" ng-true-value="'southeastern'" ng-false-value="'!southeastern'" /> 
 
     <hr /> 
 
     <h2>Results:</h2> 
 
     <table width="100%" cellpadding="5"> 
 
     <tr> 
 
      <th ng-click="OrderFilter='name'">Name</th> 
 
      <th ng-click="OrderFilter='courseType'">Course Type</th> 
 
      <th ng-click="OrderFilter='region'">Region</th> 
 
     </tr> 
 
     <tr ng-repeat="course in courses | filter:filter.searchText | searchFilter:filter.name | searchFilter:filter.courseType | searchFilter:filter.region | orderBy:orderFilter"> 
 
      <td>{{course.name}}</td> 
 
      <td>{{course.courseType}}</td> 
 
      <td>{{course.region}}</td> 
 
     </tr> 
 
     </table> 
 
    </div> 
 
    <div style="margin: 0 20px;border-left: 1px solid #000"> 
 
    
 
    </div> 
 
    <div ng-controller="secondController"> 
 
     <div class="search-filter-module"> 
 
     Search: 
 
     <br /> 
 
     <input type='search' class="search-filter" ng-model="filter.searchText" /><a title="clear input" ng-show="filter.searchText != ''" class="clear clear-search" ng-click="filter.searchText = ''"><i ng-show="filter.searchText != ''" class="material-icons">&nbsp;clear</i></a> 
 
     </div> 
 
     Course Type: 
 
     <md-switch ng-model="filter.courseType.public" aria-label="Switch 1" ng-true-value="'public'" ng-false-value="'!public'"> 
 
     Public 
 
     </md-switch> 
 
     <md-switch ng-model="filter.courseType.private" aria-label="Switch 2" ng-true-value="'private'" ng-false-value="'!private'"> 
 
     Private 
 
     </md-switch> 
 
     Region: 
 
     <md-switch ng-model="filter.region.northern" aria-label="Switch 5" ng-true-value="'northern'" ng-false-value="'!northern'"> 
 
     Northern 
 
     </md-switch> 
 
     <md-switch ng-model="filter.region.southeastern" aria-label="Switch 6" ng-true-value="'southeastern'" ng-false-value="'!southeastern'"> 
 
     Southeast 
 
     </md-switch> 
 
    </div> 
 
    </section> 
 
</div>

Вот тот же самый код в JsFiddle: http://jsfiddle.net/dtrz3060/3/

+1

В расчистке поиска текста с помощью кнопки вы не» t хотите установить его в значение «null». Он должен быть установлен в пустую строку. Я только что обновил код, чтобы исправить это. –

+1

Просто обновил ссылку JSFiddle с исправлением ошибки текстового текста. –

+0

K Scandrett: Я не могу пометить вас из-за пространства на ваше имя, я думаю. Спасибо за подсказку о значениях true/false. Да, я могу заставить его работать в ОДНОМ контроллере. Коммутаторы находятся в другом контроллере, а не в основном контроллере. – mediaguru

Смежные вопросы