How to create an attribute conditionally in AngularJS

Viewed 2310

I am trying to create aria-current attribute in an anchor only if the anchors href is equal to the current windows path. Basically, I want aria-current="page" IF the anchor in question has an href equal to the window in views path. And I do not want to create an aria-current attribute if the anchor in question does not have an href equal to the window in view path.

Is there a way to write an conditional statement inline that will create or not create an attribute in AngularJS (Angular1)?

2 Answers

I think there is no "inline way" to do this, but for this case you can create a directive

Here an Example:

yourmodule.directive('myexampleblabla', function() {
  return {
    link: function(scope, elem, attr) { 
        if(elem.attr('href') === windows.location.href){
            elem.attr('aria-current', true)
        }
    },
    restrict: 'E',
  };
});

HTML:

<a href="sample/path#a123" myexampleblabla>Your Anchor</a>

Be aware: This code in untested, but it should bring you a few steps forward.

For every case where you want to modify the DOM within a angular application you should create a directive. Read more about directives here: https://docs.angularjs.org/guide/directive

Solution: use ng-attr to conditionally create an attribute inline.

For example <div ng-attr-alt="{{<conditional statement> ? '<value to set attr to if true>' : undefined }}"

If the conditional statement does not evaluate to true then the attribute will not be created, the undefined value sets this.

Related