gespinha
gespinha

Reputation: 8487

How to get an attribute parameter in a directive

I have the following code. I am trying to inject the name from the myController scope inside the myObj directive as a nameAttr attribute.

I've assigned the name: '=nameAttr' on the directive's scope, but it doesn't seem to work.

What am I doing wrong?

https://plnkr.co/edit/qceVMl0w2gv03ZuQVQb8?p=preview

HTML

<my-obj nameAttr="name"></my-obj>

INSIDE THE 'MY-OBJ.HTML'

<h2>{{ name }}</h2>
<ol>
  <li ng-repeat="(slug, val) in loop">{{ slug }} - {{ val }}</li>
</ol>

ANGULAR

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

mod.controller('myController', myController).directive('myObj', myObject);

function myController($scope){
  $scope.name = 'John Smith';
}

function myObject(){
  return {
    restrict: 'E',
    templateUrl: 'my-obj.html',
    scope: {
      name: '=nameAttr'
    },
    controller: function($scope){
      $scope.loop = {
        'one': 'gfshfh',
        'two': '32435'
      };
    }
  };
}

Upvotes: 0

Views: 51

Answers (2)

Naga Sandeep
Naga Sandeep

Reputation: 1431

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

The normalization process is as follows:

Strip x- and data- from the front of the element/attributes.
Convert the :, -, or _-delimited name to camelCase.

Directive documentation here

Upvotes: 1

AdityaParab
AdityaParab

Reputation: 7100

In your index.html you need to write

<my-obj name-attr="name"></my-obj>

------------------^

Directives with camelCase names must be written as camel-case in your templates

Upvotes: 2

Related Questions