在我的项目中,我有一个小div,有3种选择"食物","饮料","社交".这些绑定到"AppController"上的范围变量"$ scope.option".
我有一系列ng-switch语句:
<div ng-switch on="option">
<div ng-switch-when="food">
<fooddirective></fooddirective>
</div>
<div ng-switch-when="drinks">
<drinksdirective></drinksdirective>
</div>
<div ng-switch-when="social">
<socialdirective></socialdirective>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
请注意,无论选择什么选项,食物,饮料或社交,这些只占页面的一半,因此它们都被"AppController"包围.我的意图是能够"动态加载指令"到页面中.有没有办法摆脱必须明确写入"<socialdirective></socialdirective>"甚至摆脱所有ng-switch的需要?还是有更好的选择?如果我说20或30个这些选项(即食物,饮料,社交,游戏),感觉会变得非常混乱.
如果我事先知道指令的名称,说"食物","饮料","社交".有什么方法可以做我喜欢的事情:
<div ng-switch on="option">
// code that interprets option's variable (i.e. food), appends the text "directive" after, and dynamically/lazily add it in and remove it so it behaves like an ng-switch
</div>
Run Code Online (Sandbox Code Playgroud)
我不确定是否有可能,但我正在寻找更好的替代现在我正在做的事情.任何修改后的做法的例子都很棒.
您可以使用 UI 路由器来完成此操作:
--index.html
<body>
Top Level
<div ui-view></div>
</body>
Run Code Online (Sandbox Code Playgroud)
--optionsPage.html
<select ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"></select>
<div ui-view></div>
Run Code Online (Sandbox Code Playgroud)
在选项页面中,您将使选择选项生成指向您要显示的每种指令类型的 ui-sref 链接。子状态只会更改其父状态的 ui-view,因此您可以轻松路由到正确的指令。
然后你这样定义你的路线:
.state('options.food', {
templateUrl: "partials/options.food.html"
})
.state('options.drinks', {
templateUrl: "partials/options.drinks.html"
})
Run Code Online (Sandbox Code Playgroud)
然后您可以在每个 HTML 文件中定义该指令。
(此代码的大部分内容仅取自 Angular 和 UI-Router 代码示例,但希望您能看到需要做什么。)
UI 路由器 - https://github.com/angular-ui/ui-router
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |