I am using bootstrap ui typeahead. So when the user types I want to load data asynchronously. So I created a factory which has a http req to get the data.
angular.module('customers').controller('CustomersController', ['$scope', function($scope){
$scope.searchUser = function(val) {
searchUser.getUsers(val, $scope.searchField, $scope.searchPattern, $scope.displayCount).then(function(response){
// console.log(response.data
return response.data
});
}
}]).factory('searchUser', ['$http', function($http) {
return {
getUsers: function(val, callback){
return $http({
url: '/search/user/' + val,
method: 'GET'
})
}
}
}]);
HTML:
<input type="text" ng-model="selectedUser" placeholder="Search User" typeahead="user.firstname for user in searchUser($viewValue) | filter:{firstname:$viewValue}" typeahead-on-select="onSearchItemSelect($item, $model, $label)" class="form-control">
But I keep on getting the below error
TypeError: Cannot read property 'length' of undefined
at ui-bootstrap-tpls.js:3186
at m.promise.then.u (angular.js:11319)
at m.promise.then.u (angular.js:11319)
at angular.js:11405
at ha$get.h.$eval (angular.js:12412)
at ha$get.h.$digest (angular.js:12224)
at ha$get.h.$apply (angular.js:12516)
at HTMLInputElement.l (angular.js:16632)
at HTMLInputElement.jQuery.event.dispatch (jquery.js:4409)
at HTMLInputElement.jQuery.event.add.elemData.handle (jquery.js:4095)
I almost tried all the answers accepted on stackoverflow. But I get the same error.
EDIT FYI: I tried changing the name of the function(since the function and the factory names are the same) and it didn't help. If I console log the response.data in the function I can see the returned output, but it is not returned to the type ahead.
Actually, the below code works without creating a factory. But the problem is, when I go to a different page which loads the same controller, this promise automatically keeps on gets the requests resulting in page freeze.
$scope.searchUser = function(val) {
return $http.get('/search/user/' + val)
.then(function(response){
return response.data
})
}
You should not use limitTo
filter in this way, you should first inject $filter dependency to controller and then use limitTo
filter
Should be like
$filter('limitTo')(input, limit, begin)
Code
.controller('CustomersController', ['$scope', '$filter', function($scope, $filter) {
$scope.searchUser = function(val) {
return $http.get('/search/user/' + val)
.then(function(response) {
return $filter('limitTo')(response.data, 10);
});
}
}]).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.