在我的项目中,我有一个小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>
请注意,无论选择什么选项,食物,饮料或社交,这些只占页面的一半,因此它们都被“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>
我不确定是否有可能,但我正在寻找更好的替代现在我正在做的事情.任何修改后的做法的例子都很棒.
解决方法
您可以使用UI路由器来完成此任务:
–index.html
<body> Top Level <div ui-view></div> </body>
–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>
在选项页面中,您将使选择选项生成ui-sref链接到您要显示的每种类型的指令.子状态只会更改其父状态的ui视图,因此您可以轻松地路由到正确的指令.
然后你定义你的路线:
.state('options.food',{ templateUrl: "partials/options.food.html" }) .state('options.drinks',{ templateUrl: "partials/options.drinks.html" })
然后,您可以在每个HTML文件中定义指令.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。