Having read AngularJS : Difference between the $observe and $watch methods, and the implementation of ng-href/ng-src
:
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// ...
}
}
I wonder why ng-href/ng-src
are implemented by using attr.$observe
instead of scope.$watch
. By using scope.$watch
, it looks like
link: function(scope, element, attr) {
scope.$watch(attr[normalized], function(newValue) {
// ...
})
}
then in view we could write <img ng-href="expressionFoo">
instead of <img ng-href="{{ expressionFoo }}">
.
The possible reasons I could figure out are
attr.$observe
makes a directive to work more like a normal DOM attribute. After link, I could affect the directive byattr.$set('ngHref', ...)
in another directive.- interpolate is higher level than expression. It's easier to write plain strings and multiple expressions by using interpolate.
ng-href
andng-src
both result in string attributes, so it's safe and easier to use interpolate henceattr.$observe
here.
Any idea?