【发布时间】:2016-03-29 19:05:15
【问题描述】:
我是 Angular JS 的新手,我一直在尝试使用它构建一个演示 ASP .Net MVC 应用程序。 简单地说,我有一个国家列表,每个国家都有 3 个相关城市的列表
var myModule = angular
.module("myModule", [])
.controller("myController", function ($scope) {
var countries = [
{
name: "UK",
cities: [
{name: "London"},
{name: "Birmingham" },
{name: "Manchestar" }
],
flag: "/Images/UK.gif",
foundationDate: new Date("May 20,1916"),
likes: 0,
dislikes: 0
},
{
name: "USA",
cities: [
{name: "Los Angeles"},
{name: "Houston"},
{name: "Florida"},
],
flag: "/Images/USA.png",
foundationDate: new Date("August 01,1887"),
likes: 0,
dislikes: 0
},
{
name: "INDIA",
cities: [
{ name: "Hyderabad" },
{ name: "Mumbai" },
{ name: "Kolkata" },
],
flag: "/Images/INDIA.jpg",
foundationDate: new Date("August 15,1947"),
likes: 0,
dislikes: 0
}
];
在我的视图页面中,我将它们全部显示出来。
我有一个搜索文本框,可以搜索国家名称和城市名称。为此,有 $scope.search 功能。
$scope.search = function (country) {
if ($scope.searchText == undefined) {
return true;
}
angular.forEach(country.cities, function (item) {
if (item.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) != -1)
return true;
});
return false;
}
});
这里是查看代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myModule">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/MyModuleScript.js"></script>
<style>
table, th, td {
border-collapse:collapse;
border:1px solid black;
}
th, td {
text-align:center;
vertical-align:middle;
}
</style>
</head>
<body ng-controller="myController">
Rows to display : <input type="number" step="1" min="0" max="3" ng-model="rowLimit" />
<br />
<br />
Search : <input type="text" placeholder="Search Countries & Cities" ng-model="searchText" />
<br />
<br />
<div>
<table style="padding:5px">
<thead>
<tr>
<th>Country</th>
<th>City 1</th>
<th>City 2</th>
<th>City 3</th>
<th>Flag</th>
<th>Foundation Date</th>
<th>Likes</th>
<th>Dislikes</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="country in countries | orderBy : '+foundationDate' | limitTo: rowLimit | filter : search">
<td>{{ country.name }}</td>
<td ng-repeat="city in country.cities">
{{ city.name }}
</td>
<td><img ng-src="{{ country.flag }}" style="height:100px;width:150px"/> </td>
<td>{{ country.foundationDate | date : "dd/MM/yyyy" }}</td>
<td>{{ country.likes }}</td>
<td>{{ country.dislikes }}</td>
<td><input type="button" value="Like" ng-click="incrementLikes(country)"</td>
<td><input type="button" value="Dislike" ng-click="incrementDislikes(country)"</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
但是搜索功能不正常。 这是html视图页面的截图
不知何故,我知道 search 功能的逻辑设计并不正确。 有人可以帮我解决吗?
【问题讨论】:
-
过滤器:搜索文本,而不是搜索。它与您的 ng-model 匹配
-
其实没有。我已经搜索了整个国家/地区名称,并且城市名称也与该国家/地区相关联。所以 $scope.search 就在那里。
-
另外,佛罗里达不是一个城市,而是一个州
-
从技术上讲,有一个佛罗里达州,俄亥俄州,但是是的,它主要被称为一个州。
-
对不起,我不好。这根本不是故意的。
标签: javascript angularjs foreach