Iam学习使用纯AngularJS进行自动完成,以及我从youtube视频中复制的以下代码。
请告诉我这个特别的部分
控制器
QQuickItem
});
服务
myApp.controller("myWeatherContrl", function ($scope, weatherService) {
$scope.title = "Weather App";
weatherService.getCities().then(function (response) {
$scope.data = response;
//console.log("Say Hi", $scope.data);
})
$scope.complete = function (string) {
var output = [];
angular.forEach($scope.data, function (city) {
if (city.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(city);
}
});
$scope.filterCity = output;
};
$scope.fillTextbox = function(string){
$scope.city = string;
$scope.hidethis = true;
};
HTML(指令)
myApp.service("weatherService", ['$http', '$q', function ($http, $q) {
return {
getCities: function () {
return $http.get('data/data.json');
}
};
}]);
的index.html
<div class="input-group">
<input type="text" id="city" ng-keyup="complete(city)" placeholder="Enter City Name" class="form-control" ng-model="city"/>
<ul class="list-group">
<li class="list-group-item" ng-model="hidethis" ng-hide="hidethis" ng-click="fillTextbox(citydata)" ng-repeat="citydata in filterCity">
{{citydata}}
</li>
</ul>
我收到错误 city.toLowerCase不是函数
请帮我解决这个问题
答案 0 :(得分:1)
试试这个:
var myApp = angular.module("myApp", []);
myApp.controller("myWeatherContrl", function($scope, weatherService) {
$scope.title = "Weather App";
$scope.obj = {};
$scope.obj.data = [];
weatherService.getCities().then(function(response) {
angular.forEach(response.data, function(state) {
angular.forEach(state, function(city) {
if (typeof city === "string") {
$scope.obj.data .push(city);
}
});
});
console.log("Say Hi", $scope.data);
})
$scope.complete = function(string) {
var output = [];
if (string.length >= 3) {
angular.forEach($scope.obj.data , function(city) {
if (city.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(city);
}
});
}
$scope.filterCity = output;
};
$scope.fillTextbox = function(string) {
$scope.city = string;
$scope.hidethis = true;
};
});
myApp.service("weatherService", ['$http', '$q', function($http, $q) {
return {
getCities: function() {
return $http.get('https://api.myjson.com/bins/pufq5');
}
};
}]);
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myWeatherContrl">
<div class="input-group">
<input type="text" id="city" ng-keyup="complete(obj.city)" placeholder="Enter City Name" class="form-control" ng-model="obj.city" />
<ul ng-if="obj.data.length>0" class="list-group">
<li style="cursor:pointer" class="list-group-item" ng-click="obj.city = citydata;obj.data={};" ng-repeat="citydata in filterCity track by $index">
{{citydata}}
</li>
</ul>
</div>
</body>
&#13;
答案 1 :(得分:0)
执行weatherService.getCities().then(function (response)...
时,响应不得返回字符串列表。
这意味着当您调用angular.forEach($scope.data, function (city) {
时,city
变量未填充字符串。
在console.log(city)
循环中添加forEach
以协助调试。