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

查看:41
本文介绍了检查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'
  }
}

理想情况下,它将直接绑定到范围,以便可以在模板中使用.但是,绑定变量的值为 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参数中是否存在属性,并将其分配给指令的隔离范围内的变量./p>

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天全站免登陆