Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get the attribute value of my custom directive?

The angularjs code:

app.directive('test', function(){
  return {
    restrict: 'A',
    scope: {
      myId: '@'
    },
    link: function(scope) {
      alert(scope.myId);
    }
  }
});

You can see there is a scope: { myId: '@' } in the directive.

And the html code:

<div test my-id='123'></div>

You can see I defined a my-id='123'.

I hope the directive will alert 123, but it alerted undefined. Where is my mistake?

PS: here is a live demo: http://plnkr.co/edit/sL69NqWC70Qfwav5feP2?p=preview

like image 875
Freewind Avatar asked Mar 05 '13 06:03

Freewind


People also ask

What is directive attribute?

Attribute directives are used to change the appearance or behavior of an element. Examples of attributes directives are ngStyle , ngClass , ngModel. ngStyle — used to apply styles that will change the appearance. ngClass — used to apply CSS classes to change the appearance.

How do you create an attribute directive?

Steps to create a custom attribute directiveAssign the attribute directive name to the selector metadata of @Directive decorator. Use ElementRef class to access DOM to change host element appearance and behavior. Use @Input() decorator to accept user input in our custom directive.

What is the difference between structural directive and attribute directive?

There are two types of directives in Angular. Attribute directives modify the appearance or behavior of DOM elements. Structural directives add or remove elements from the DOM.

Which decorator is used while creating custom attribute directives?

Creating a Custom Attribute Directive To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element's background color.


1 Answers

You need to $observe attributes (as described in the "Attributes" section of http://docs.angularjs.org/guide/directive) to get the proper value of interpolated attributes.

Here is a working plunk: http://plnkr.co/edit/NtIHmdoO7IAEwE74ifB5?p=preview

This is essentially duplicate of the angularjs : logging scope property in directive link function displays undefined. It should be also noted that the PR https://github.com/angular/angular.js/pull/1555 was merged recently and your plunker should work without using $observe in the future versions of AngularJS.

--

The demo in question is worked in latest version: 1.1.3, you can try it (and change the angularjs url to 1.1.3).

like image 78
pkozlowski.opensource Avatar answered Oct 12 '22 13:10

pkozlowski.opensource