How do you “require” an attribute in the angularjs directive?

Let's say I have a directive called 'myDirective'. How can I require that all instances of this directive must have a certain attribute for them, for example, below:

<div data-my-directive data-my-variable='blue'></div>
+1
source share
2 answers

I'm not sure if you might need an attribute, but you can check if a value has been 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);
        }
}
+3
source

, - , "myVariable" , , , myVariable , : "myVariable" , myDirective.

0

Source: https://habr.com/ru/post/1539033/


All Articles