6


我正在尝试为选择元素动态更改选项模板。这是我想要做的,我有选择选项,这将允许用户在选择学生时选择他们想要查看的信息类型。如果用户选择“基本”,那么我只显示学生类的 Id 和 Name 属性。如果用户选择“详细信息”,那么我会显示 Id、Name 和 Grade。当前的实现是

<!DOCTYPE html>
<html ng-app>
<head>
    <title></title>
    <script type="text/ng-template" id="Basic">
        <select ng-model="selectedItem">
        <option ng-repeat="student in Students">
           {{student.Id}} - {{student.Name}}
        </option>
        </select>
    </script>
     <script type="text/ng-template" id="Detail">
        <select ng-model="selectedItem">
        <option ng-repeat="student in Students">
           {{student.Id}} - {{student.Name}} -- {{student.Grade}}
        </option>
        </select>
    </script>
</head>
    <body>
        <div ng-controller="TemplateCtrl">
            Details Level: <select ng-model="detailLevel" ng-options="c.Id for c in Details"></select>
            <div ng-include="detailLevel.Id"></div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
        <script src="Scripts/TemplateCtrl.js"></script>
    </body>
</html>


如您所见,我在 ng-template 'Basic' 和 'Detail' 中都复制了代码。最初我正在尝试类似以下的事情

<script type="text/ng-template" id="Basic">
           {{student.Id}} - {{student.Name}}
    </script>
<script type="text/ng-template" id="Detail">
           {{student.Id}} - {{student.Name}} -- {{student.Grade}}
    </script>


但是当我尝试在侧标签中执行 ng-include 时,浏览器不喜欢。我可能在这里遗漏了一些简单的东西,在这里创建重复代码气味我做错了什么?谢谢,

4

1 回答 1

3

也许您可以尝试使用ng-switch 指令,而不是模板。然后以下应该工作:

<!DOCTYPE html>
<html ng-app>
<head>
    <title></title>
</head>
    <body>
        <div ng-controller="TemplateCtrl">
            Details Level: <select ng-model="detailLevel" ng-options="c.Id for c in Details"></select>
            <div ng-switch="detailLevel">
                <div ng-switch-when="Basic">
                    <select ng-model="selectedItem">
                        <option ng-repeat="student in Students">{{student.Id}} - {{student.Name}}</option>
                    </select>
                </div>
                <div ng-switch-when="Detail">
                    <select ng-model="selectedItem">
                        <option ng-repeat="student in Students">{{student.Id}} - {{student.Name}} -- {{student.Grade}}</option>
                    </select>
                </div>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
        <script src="Scripts/TemplateCtrl.js"></script>
    </body>
</html>
于 2013-04-08T13:11:38.323 回答