[英]How to implement Cascading Drop Down List in MVC SPA using Angular JS?
我正在嘗試使用angularjs學習MVC單頁應用程序(SPA),而且我不知道如何在其中實現級聯下拉列表。 任何幫助表示贊賞。
提前致謝,
娜迦·費納德拉(Naga Phaneendra)。
我認為您想在級聯下拉列表中支持Ajax。 這個指向JSFIDDLE的鏈接包含了一個使用Ajax和Static列表級聯DDL的好例子。 http://jsfiddle.net/annavester/Zd6uX/
級聯DDL的HTML:
<div ng-controller="AjaxCtrl">
<h1>AJAX - Oriented</h1>
<div>
Country:
<select id="country" ng-model="country" ng-options="country for country in countries">
<option value=''>Select</option>
</select>
</div>
<div>
City: <select id="city" ng-disabled="!cities" ng-model="city" ng-options="city for city in cities"><option value=''>Select</option></select>
</div>
<div>
Suburb: <select id="suburb" ng-disabled="!suburbs" ng-model="suburb" ng-options="suburb for suburb in suburbs"><option value=''>Select</option></select>
</div>
如您所見,我們使用ng-options填充DDL中的數據。 DDL將在$ scope中返回所選對象。 因此,請不要擔心如何處理將出現在DDL選項中的ID和標題。
接下來的控制器代碼如下:
function AjaxCtrl($scope) {
$scope.countries = ['usa', 'canada', 'mexico', 'france'];
$scope.$watch('country', function(newVal) {
if (newVal) $scope.cities = ['Los Angeles', 'San Francisco'];
});
$scope.$watch('city', function(newVal) {
if (newVal) $scope.suburbs = ['SOMA', 'Richmond', 'Sunset'];
});
}
如您所見,我們使用$ watch監視DDL中的更改。 替換此行代碼
if (newVal) $scope.cities = ['Los Angeles', 'San Francisco'];
使用觸發Ajax請求以基於newVal.ID選擇數據並使用$ http.get向城市填充結果的代碼
通常,通過生成某種嵌套的html結構(通常是<ul>
和<li>
標記),然后應用樣式表和一些javascript來顯示或隱藏子元素,直到單擊它們,才能完成這種菜單。 在線上有十億個示例,因此我將把答案集中在如何生成嵌套的html(這是最困難的部分)上。
您可以使用遞歸ng-repeat
和內聯模板來完成此操作。
首先,您需要在您的范圍內建立某種樹模型。
var app = angular.module('menuApp', []);
app.controller('MenuController', function($scope) {
$scope.menu = [
{
label : "Main Menu",
url: "#/main",
children: [
{ label: "First Child", url: "#/main/1" },
{ label: "Second Child", url: "#/main/2",
children: [
{ label: "First Grandchild", url: "#/main/2/1" },
{ label: "Second Grandchild", url: "#/main/2/2" }
]
},
{ label: "Third Child", url: "#/main/3",
children: [
{ label: "Third Grandchild", url: "#/main/3/3" },
{ label: "Fourth Grandchild", url: "#/main/third/fourth",
children: [
{ label: "First Great-Grandchild", url: "#/main/3/4/1" },
{ label: "Second Great-Grandchild", url: "#/main/3/4/2" }
]
}
]
}
]
}
];
});
現在,您可以執行此操作。
<ul ng-controller="MenuController">
<li ng-repeat="item in menu" ng-include="'menu-tree.html'"></li>
</ul>
<script type="text/ng-template" id="menu-tree.html">
<a href="{{item.url}}">{{item.label}}</a>
<ul>
<li ng-repeat="item in item.children" ng-include="'menu-tree.html'"></li>
</ul>
</script>
這是一個工作示例的鏈接。 http://plnkr.co/edit/V6aVx0JeBFwrUgPZs0vw?p=預覽
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.