Paul I
Paul I

Reputation: 942

Angular directive link attrs

I was going through the Angular documentation and had a question about directives. This is in regards to the "Creating a Directive that Manipulates the DOM" section of http://docs.angularjs.org/guide/directive

I added some console.log() statements in the following code:

scope.$watch(attrs.myCurrentTime, function(value) {
  format = value;
  updateTime();
});

like so:

scope.$watch(attrs.myCurrentTime, function(value) {
  console.log('attrs.myCurrentTime = ', attrs.myCurrentTime);
  console.log('value = ', value);
  format = value;
  updateTime();
});

When changing the contents of the 'Date format' text box, I was expecting to see the same value in both console.log() statements, namely the actual value of the parent scope's format attribute, but the first console.log() still shows 'format' as a string.

Why do you think this might be?

Link to code: http://plnkr.co/edit/8LkKBiIpqTn0gr5fXQZL?p=preview

Upvotes: 1

Views: 2023

Answers (1)

gkalpak
gkalpak

Reputation: 48211

First of all, there is no parent scope. Since your directive does not declare a scope (either isolate or "normal") there is no scope created, so the element shares the same scope as its parent-element.
A quick and easy way to check the scope of an element using DevTools is this:
1. Select the element in the "Elements" panel.
2. In the console, execute the command: angular.element($0).scope();


So, what is actually going on ?

attrs.myCurrentTime represents a plain old string value (namely "format").
So console.log('attrs.myCurrentTime = ', attrs.myCurrentTime); is equivalent to console.log('attrs.myCurrentTime = ', 'format');

In the same way, scope.$watch(attrs.myCurrentTime, ...) is equivalent to scope.$watch('format', ...).
According to the docs on Scope, if the first argument of $watch is a string it is "evaluated as expression", which in this case means as scope['format'] (which of course returns the current value of the scope's format property).

Upvotes: 4

Related Questions