I've written a directive with an isolate scope.
app.directive('myDirective', function() {
return {
restrict: 'E',
scope {
attr1: '@',
attr2: '@',
noValueAttr: // what to put here?
},
link: function(scope, elem, attrs) {
// how to check here if noValueAttr is present in mark-up?
}
};
});
the html could be
<my-directive attr1='...' attr='...' ... no-value-attr>
or
<my-directive attr1='...' attr='...' >
I am wondering how to use (and have the directive detect if it's there or not) an optional attribute which has no assigned value. Thanks.
scope is an AngularJS scope object. element is the jqLite-wrapped element that this directive matches. attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values. controller is the directive's required controller instance(s) or its own controller (if any).
Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.
Restrict. Angular allows us to set a property named restrict on the object we return on our directive definition. We can pass through a string with certain letters letting Angular know how our directive can be used. function MyDirective() { return { restrict: 'E', template: '<div>Hello world!
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Just use attrs.hasOwnProperty('noValueAttr')
in the link function to test whether the attribute is present or not.
Don't forget the attribute in markup would be no-value-attr
, not noValueAttr
like you showed.
link: function(scope, elem, attrs) {
if (attrs.hasOwnProperty('noValueAttr'))
// attribute is present
else
// attribute is not present
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With