我正在尝试为select元素动态更改选项模板。这是我想要做的,我有选择选项,这将允许用户选择他们在选择学生时想要看到的信息类型。如果用户选择“基本”,那么我只显示Student类的Id和Name属性。如果用户选择“详细信息”,则显示,ID,名称和等级。目前的实施是
<!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时,浏览器并不喜欢。我可能会在这里遗漏一些简单的东西,我在这里创建重复的代码气味我做错了什么?
谢谢,
答案 0 :(得分:3)
也许您可以尝试使用ng-switch directive,而不是模板。 那么以下应该有效:
<!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>