George R
George R

Reputation: 3860

angularjs - Getting the binding expression from an attribute (not the resolved value)

I'm making a directive that cross fades between images based on this: http://www.bennadel.com/blog/2497-Cross-Fading-Images-With-AngularJS.htm

Instead of watching a particular field, i'd like to watch whatever the image is binding to in ngSrc. So rather than (coffeescript):

 $scope.$watch "data.ActiveImage", (newValue, oldValue) ->

I'd like to use:

 $scope.$watch attributes['ngSrc'], (newValue, oldValue) ->

Where the DOM element looks like:

<img cross-fade-on-change ng-src="{{data.ActiveImage}}"/>

The problem is, the watch expression is resolving to the bound url, rather than the binding expression. How/can I do this?

Upvotes: 1

Views: 382

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32397

You should use $observe instead of $watch:

attrs.$observe 'ngSrc', (value) ->
  • $observe is used for watching attribute interpolations ($interpolate).
  • $watch is used for evaluating expressions against a scope ($parse).

From the docs:

$observe(key, fn)

Observes an interpolated attribute.

$watch(watchExpression, listener, objectEquality)

Registers a listener callback to be executed whenever the watchExpression changes.

Upvotes: 1

Related Questions