加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何更好地组织角度的动态加载指令?

发布时间:2020-12-17 06:58:48 所属栏目:安全 来源:网络整理
导读:在我的项目中,我有一个小div,有3种选择“食物”,“饮料”,“社交”.这些绑定到“AppController”上的范围变量“$scope.option”. 我有一系列ng-switch语句: div ng-switch on="option"div ng-switch-when="food"fooddirective/fooddirective/divdiv ng-swit
在我的项目中,我有一个小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文件中定义指令.

(这些代码大部分来自Angular和UI-Router代码示例,但希望您能看到您需要做什么.)

UI路由器 – https://github.com/angular-ui/ui-router

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读