Я только начинаю со стека MEAN и не совсем уверен, какой оптимальный способ обмена данными и обнаружения изменений в другом контроллере будет. У меня есть ввод текста/поиска в заголовке, логика для него в одном контроллере (TypeheadController), и после того, как кто-либо либо выберет значение из списка typeahead/autocomplete, либо нажал кнопку поиска, я хочу, чтобы Searchresultscontroller обнаружил изменение для свойства на startSearchService и использовать это значение для загрузки результатов поиска.
Основной шаблон layout.server.html
<body>
<header ng-controller="HeaderController">
<nav></nav>
<div ng-controller="TypeaheadController">
<input type="text" typeahead-on-select="onSelect($item, $model, $label)" />
</div>
</header>
//**this is where angular-ui-router.js will load templates into.**
<section data-ui-view></section>
</body>
client.searchresults.html.
<div ng-controller="SearchresultsController">
**//the SearchresultsController will pull JSON search result data and populate this template. Presentation logic omitted for clarity**
</div>
startSearchService
angular.module('myapp').service('startSearchService', function() {
this.searchString = "";
});
TypeaheadController
var TypeaheadController = function($scope, $http, startSearchService)
{
//function that pulls and maps name suggestion for typeahead goes here.
//Upon user selecting a typeahead suggestion, update the property on the service instance. OnSelect will fire when user selects suggestion.
$scope.onSelect = function(item, model, label) {
startSearchService.searchString = item;
}
};
SearchresultsController
var SearchresultsController = function($scope, $http, startSearchService)
{
//This controller should make the actual request to pull search results
// after which the state will be changed to /searchresults/ and the //client.searchresults.html template will be loaded and populated. Most Typeahead //directives and other code omitted for clarity.
//Upon user selecting a typeahead suggestion update the properties on the //service.
//OnSelect will fire when user selects suggestion.
**//I need logic to detect change in startSearchService.searchString and then I will use that value to pull in search results. The below $on function does not work and it wrong way to watch for change**
startSearchService.searchString.$on('change', function(ev, args) {
//Pull data from Server
//then change $location to /searchresults/ and client.searchresults.html will //load and $scope data will be binded to it.
});
};
Сделать startSearchService
выставлять функции, а не поле:
angular.module('myapp').factory('startSearchService', function() {
var searchString = "";
return {
set: function(s) {
searchString = s;
},
get: function() {
return s;
}
};
});
Затем сделайте это трансляцию события каждый раз, когда изменяется переменная searchString:
angular.module('myapp').factory('startSearchService', function($rootScope) {
var searchString = "";
return {
set: function(s) {
searchString = s;
$rootScope.$broadcast('searchStringChanged');
},
get: function() {
return s;
}
};
});
Из вашего TypeaheadController
вызовите функцию set(), чтобы изменить строку поиска.
Из вашего SearchresultsController
прослушайте событие 'searchStringChanged'
:
$scope.$on('searchStringChanged', function() {
var searchString = startSearchService.get();
// TODO do something with the new searchString
});