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
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With