检查属性的存在,在角指令 [英] Check existence of attribute in Angular Directive

查看:118
本文介绍了检查属性的存在,在角指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时可以检查给定的属性是否在指令present,理想地使用隔离范围或在最坏的情况下的属性对象

Is is possible to check whether a given attribute is present in a directive, ideally using isolate scope or in a worst case scenario the attributes object.

使用看起来像这样一个指令<项目状态>< /项目> ,我想有条件地呈现状态图标,但只有在状态属性为present。

With a directive that looked something like this <project status></project>, I want to conditionally render a status icon, but only if the status attribute is present.

return {
  restrict: 'AE',
  scope: {
    status: '@'
  },
  link: function(scope, element, attrs) {
    scope.status === 'undefined'
  }
}

理想情况下,这将是直绑定到的范围,因此,它可以在模板中使用。但是,绑定变量的值未定义。这同样适用于&安培; 只读 = 双向绑定。

Ideally, it would be bound straight to the scope, so that it could be used in the template. However, the bound variable's value is undefined. The same goes for & read-only and = two-way bindings.

我知道它是平凡的通过增加一个&LT解决;项目状态='真'&GT;&LT; /项目&GT; ,但我会经常使用的指令,我宁愿没有。 (XHTML有效性,是不是一个问题)。

I know that it's trivially solved by adding a <project status='true'></project>, but for directives that I will use frequently, I'd rather not have to. (XHTML validity, is not an issue).

推荐答案

要做到这一点的方法是检查链接功能的ATTRS参数中的属性的存在,并分配给你的指令的分离范围内的变量。

The way to do this is to check for the existence of the attributes within the link function's attrs parameter, and assign this to variables within your directive's isolate scope.

scope:{},
link: function(scope, element, attrs){
  scope.status = 'status' in attrs;
},

这应该工作而无需你的链接功能中使用if语句。

This should work without having to use an if statement within your link function.

这篇关于检查属性的存在,在角指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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