问题
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