我是Angular JS的新手,我一直在嘗試使用它構建一個演示ASP.Net MVC應用程序。 簡單來說,我有3個相關城市在Angular JS中循環使用
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視圖頁面
截圖不知何故,我知道這個邏輯並不正確地設計爲搜索功能。 有人能幫助我嗎?
filter:searchText,而不是搜索。它匹配你的ng模型 –
其實沒有。我搜索了國家名稱和與該國相關的城市名稱。所以$ scope.search就在那裏。 – StrugglingCoder
另外,佛羅里達州不是一個城市,但一個州 – Austin