AngularJS:做指令动态模板和替代选项的正确方法是什么? [英] AngularJS: Correct way of doing directive with dynamic template and replace option on?

查看:314
本文介绍了AngularJS:做指令动态模板和替代选项的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最简单的(正确)的方式有动态模板作为指令和保持替换选项(想对我的模板所有的属性)。

What is the easiest(and correct) way to have dynamic templates for directive and keep replace option (want to have all the attributes on my template).

我试图创建链接指令,这将是扩展用户界面路由器/ UI-SREF:当状态是当前状态 - 我们只显示文本(而不是链接)

I'm trying to create "link" directive that will be extension for ui-router/ui-sref : when the state is current state - we show just a text (not a link).

这不是通过编译做只是动态模板的问题(或$编译服务),但我怎么能保持替换选项,通过了所有指令属性的模板。

It's not a problem to do just dynamic templates via compile(or $compile service), but how could I keep replace option on, that passes all the directive attributes to the template.

所以我想有

<ui-link ui-sref="dashboard.common" class="nav-alt__item">Dashboard</ui-link>

如同

<a ui-sref="dashboard.common" class="nav-alt__item">Dashboard</a>

在一种情况下以及

in one case and

<span ui-sref="dashboard.common" class="nav-alt__item">Dashboard</span>

在另一个。

其实我不需要 UI-SREF 跨度,但它不是一个大问题。

actually I don't need ui-sref for span, but it's not a big issue.

可能有已经存在的扩展解决方案,为UI的路由器。

May be there is already existing extension solutions for ui-router.

推荐答案

您可以为模板提供的函数具有动态模板,但通常这是错误的方式,因为你没有插属性值或其他任何东西有没有可能对决策有用的。

You can have dynamic templates by supplying a function as template, but usually it is the wrong way because you don't have interpolated attribute values or anything else there that could be useful for making decisions.

嵌套指令是什么角是舒服。

Nesting directives are what Angular is comfortable with.

app.directive('uiLink', function () {
  return {
    scope: {
      uiSref: '@',
      current: '@?'
    },
    transclude: true,
    template: [
      '<a ng-if="!current" ui-sref="{{uiSref}}" ng-transclude></a>',
      '<span ng-if="current" ng-transclude></span>',
    ].join('')
  };
});

替换不是当有模板中的多个根元素的选项。所以可选属性(类等)应属于 UI链接,并且没有被翻译成嵌套元素。

replace is not a option when there are multiple root elements in a template. So optional attributes (class, etc) should belong to ui-link and don't have to be translated to nested elements.

这篇关于AngularJS:做指令动态模板和替代选项的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆