检查 AngularJs 指令中的属性是否存在 [英] Check existence of attribute in AngularJs Directive

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

问题描述

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

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.

使用类似于 <project status></project> 的指令,我想有条件地呈现一个状态图标,但前提是 status 属性存在.

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.

我知道通过添加 <project status='true'></project> 可以轻松解决它,但是对于我经常使用的指令,我宁愿没有到.(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.

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

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