Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of attribute in AngularJs Directive

Is is possible to check whether a given attribute is present in a directive, ideally using isolate scope or in a worst case scenario the attributes object.

With a directive that looked something like this <project status></project>, I want to conditionally render a status icon, but only if the status attribute is present.

return {   restrict: 'AE',   scope: {     status: '@'   },   link: function(scope, element, attrs) {     scope.status === 'undefined'   } } 

Ideally, it would be bound straight to the scope, so that it could be used in the template. However, the bound variable's value is undefined. The same goes for & read-only and = two-way bindings.

I know that it's trivially solved by adding a <project status='true'></project>, but for directives that I will use frequently, I'd rather not have to. (XHTML validity, is not an issue).

like image 856
Dan Prince Avatar asked Sep 12 '14 15:09

Dan Prince


People also ask

What is =? In AngularJS?

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute.

What is Angular attribute directive?

Angular attribute directives are a number of built-in directives that we can add to our HTML elements that give them a dynamic behavior. In summary, an attribute directive changes the appearance or behavior of a DOM element.

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 are the directives of 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

The way to do this is to check for the existence of the attributes within the link function's attrs parameter, and assign this to variables within your directive's isolate scope.

scope:{}, link: function(scope, element, attrs){   scope.status = 'status' in attrs; }, 

This should work without having to use an if statement within your link function.

like image 176
James Jackson Avatar answered Sep 18 '22 03:09

James Jackson