Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute without value in AngularJS directive

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.

like image 237
oikonomiyaki Avatar asked Dec 04 '14 03:12

oikonomiyaki


People also ask

What is attrs in AngularJS?

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).

What does $compile do in AngularJS?

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.

What is restrict in AngularJS directive?

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!

What are the directives in AngularJS?

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.


1 Answers

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

    }
like image 188
GregL Avatar answered Nov 15 '22 07:11

GregL