1

For some reason Angular isn't catching my data-src

When I do this:

<div foo data-src="{{ my_url }}"></div>

I get back nothing. However, it works when I manually type it: i.e

<div foo data-src="blah"></div>

What am I doing wrong here?


More of my code:

var foo = angular.module('foo', []);

foo.directive('foo', function ($document, $rootScope, $http, $resource) {

return {
      restrict: 'A',
      scope: true,
      link: function (scope, elem, attrs) {
        console.log(attrs.src)
      }
  });
3
  • My guess is that angular evaluates your data-src before it evaluates {{ my_url }} Commented Feb 20, 2014 at 22:44
  • @Tom Yes, I'm pretty sure this is the problem. Would you happen to know a fix? Commented Feb 20, 2014 at 22:46
  • Shouldn't that be data-ng-src? The browser evaluates the source before angular replaces the content. You can use ng-src or data-ng-src, that should work, but it will send two requests: one invalid without the placeholder filled in, then the correct one. Commented Feb 20, 2014 at 22:52

1 Answer 1

1

[Edit]

I forgot to use camelCase for the attribute name when calling attrs.$observe(). Also, it looks like you do need to use ng-data-source). Correction made below...

You want to use attrs.$observe() in the link function for your directive. Angular will watch the attribute and execute a callback so the directive can be notified when the value of the interpolated expression changes.

Here's a link to a fiddle created by Mark Rajcok that demonstrates it. And a link to the documentation as well.

Finally, here is some sample code using your directive:

var foo = angular.module('foo', []);

foo.directive('foo', function ($document, $rootScope, $http, $resource) {

return {
      restrict: 'A',
      scope: true,
      link: function (scope, elem, attrs) {
        attrs.$observe('ngDataSrc', function(newValue) {
          console.log('interpolated value', newValue);
        }
      }
  });
Sign up to request clarification or add additional context in comments.

2 Comments

The documentation says it will call the callback immediately (on the next $digest) when you do the $observe, and then anytime the value changes. Is the value undefined the first time? If so, maybe you can just ignore that the first time...
Thank you. I ended up doing this if (newValue != undefined)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.