你如何在 angularjs 指令上“要求"一个属性? [英] How do you 'require' an attribute on an angularjs directive?

查看:19
本文介绍了你如何在 angularjs 指令上“要求"一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为myDirective"的指令.我怎么能要求这个指令的所有实例都必须有一个特定的属性,比如波纹管:

解决方案

我不确定您是否可以完全要求属性,但是您可以检查是否提供了值,如果没有则抛出异常.例如,来自 ng-repeat:

link: function($scope, $element, $attr, ctrl, $transclude){var 表达式 = $attr.ngRepeat;var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,lhs、rhs、valueIdentifier、keyIdentifier、hashFnLocals = {$id: hashKey};如果(!匹配){throw ngRepeatMinErr('iexp', "'_item_ in _collection_[ track by _id_]' 形式的预期表达式,但得到了 '{0}'.",表达);}}

Say I have a directive called 'myDirective'. How can I require that all instances of this directive must have a specific attribute on them such as bellow:

<div data-my-directive data-my-variable='blue'></div>

解决方案

I am not sure you can require an attribute outright, but you can check if a value was provided and throw an exception if not. For example, from ng-repeat:

link: function($scope, $element, $attr, ctrl, $transclude){
    var expression = $attr.ngRepeat;
    var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
        trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
        lhs, rhs, valueIdentifier, keyIdentifier,
        hashFnLocals = {$id: hashKey};

        if (!match) {
            throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
            expression);
        }
}

这篇关于你如何在 angularjs 指令上“要求"一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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