How do you 'require' an attribute on an angularjs directive?

落爺英雄遲暮 提交于 2019-12-11 11:22:22

问题


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>

回答1:


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);
        }
}



回答2:


i think the best way to do that is to check attributes and see if "myVariable" exist and throw an exception if it doesn't, but if you must require that in directive definition the only way is to make myVariable another directive and use require:'myVariable' on the original directive e.g myDirective.



来源:https://stackoverflow.com/questions/23370448/how-do-you-require-an-attribute-on-an-angularjs-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!