Home » Javascript » Angular directive not obtaining parameter from html?

Angular directive not obtaining parameter from html?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a navigation directive that I am trying to be able to use on different sections of my site.

My directive code is as follows:

var directives = angular.module('directives', []);

directives.directive('nav', function() {
  return {
    restrict: "E",
    scope: {
      whereTo: '@'
    },
    templateUrl: "partials/_nav.html"
  }
});

the _nav.html is as follows

<div class="nav">
  <header>
    <div class="image-div small">
      <img src="assets/images/logo.jpg" alt="temp logo">
    </div>
    <ul>
      <li class="home" ui-sref-active="active"><a ui-sref="{{whereTo}}-home">Panel</a></li>
      <li class="profile" ui-sref-active="active"><a ui-sref="{{nav.whereTo}}-profile">Profile</a></li>
      <li class="search" ui-sref-active="active"><a ui-sref="{{whereTo}}-stats">Stats</a></li>
    </ul>
  </header>
</div>

and I am calling it from html as so,

<nav whereTo="admin"></nav>

The “admin” parameter isn’t showing up in the directive when the program is run and I cannot figure out why.

Answers:

Read the Normalization section of the angular docs (https://docs.angularjs.org/guide/directive).

“AngularJS normalizes an element’s tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).”

You need to use where-to in the dom instead of whereTo.

See the attached plunker:

https://plnkr.co/edit/LKskSKTb1fmofDWRixQO