我有这样的申请:
---------------
NAVBAR [SEARCH] (< navCtrl)
---------------
TR NG GRID (< gridCtrl)
我想触发一个函数,如果在搜索栏中输入了一些内容,该搜索栏位于将myData
对象(从我的API)加载到gridCtrl
的导航栏中。
如何实现这样的目标?
答案 0 :(得分:2)
我已经添加了一些示例实现作为答案,如上所述。
.factory('SearchService', function($http, SearchedDataCache) {
var searchService = {};
var requestURl = '';
searchService.search = function(searchquery) {
// Calling the back-end to do the actual search
requestURl = '/search_url';
return $http.post(requestURl, searchquery)
.then(function(res) {
// Search success, process data
SearchedDataCache.setSearchResults(res.data);
// Return the promise
return res.data;
}, function(res) {
// Operation Failed
console.log('<SearchService> Search failed ' + res.data);
return res.data;
}
);
};
return searchService;
})
.service('SearchedDataCache', function($rootScope) {
var searchResults = []; // Holds the current search results
// Assign search results
this.setSearchResults = function(searchResponse) {
$.each(searchResponse, function(index, element) {
searchResults.push(element);
});
console.log('<SearchedDataCache.results> # of search results ' + searchResults.length);
// This can be used if we use broadcast message event based data update
$rootScope.$broadcast('search-store-updated');
};
this.getSearchResults = function() {
return searchResults;
};
return this;
})
.controller('SearchGridController', [ '$scope', 'SearchedDataCache',
// For broadcast message event based implementation
function($scope, SearchedDataCache) {
$scope.$on('search-store-updated', function () {
$scope.results = SearchedDataCache.getSearchResults();
// Use the results to display
});
}
// Data model reference based implementation
$scope.results = SearchedDataCache.getSearchResults();
$scope.$watch('results', function() {
// Use the results to display
});
])