0

我正在尝试使用 angularjs 学习 MVC 单页应用程序(SPA),但我不知道如何在其中实现级联下拉列表。任何帮助表示赞赏。

提前致谢,

纳迦法南德拉。

4

2 回答 2

2

我认为您希望在您的级联下拉列表中支持 Ajax。这个指向 JSFIDDLE 的链接包含使用 Ajax 和静态列表的级联 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 和 title。

接下来控制器代码如下:

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 填充城市结果

于 2013-10-06T08:40:40.750 回答
1

大多数时候,这种菜单是通过生成某种嵌套的 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

于 2013-06-24T13:39:53.293 回答