我想學習MVC單頁應用程序(SPA)與angularjs,我不知道如何實現級聯下拉列表中。任何幫助表示讚賞。如何在MVC SPA中使用Angular JS實現級聯下拉列表?
在此先感謝,
娜迦Phaneendra。
我想學習MVC單頁應用程序(SPA)與angularjs,我不知道如何實現級聯下拉列表中。任何幫助表示讚賞。如何在MVC SPA中使用Angular JS實現級聯下拉列表?
在此先感謝,
娜迦Phaneendra。
大多數這種菜單是由產生某種嵌套的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=preview
我認爲,要支持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選項來填充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'];
});
}
,你可以看到,我們使用$看觀看的DDL變化。 與觸發Ajax請求使用$ http.get
選擇基於newVal.ID數據和結果填入城市的代碼替換這行代碼if (newVal) $scope.cities = ['Los Angeles', 'San Francisco'];