Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ng-src doesn't update in AngularJS view

I'm using the following code in my Angular app to display an image:

<img ng-src="{{planet.image_url}}" class="planet-img"/>

And I'm using $watch to change the image_url attribute when other events happen. For example:

$scope.$watch('planet', function(planet){
  if (planet.name == 'pluto') {
     planet.image_url = 'images/pluto.png';
  }
});

Using console logs, I see that the model attributes are changing just like I want them to, but these changes are not reflected in the DOM. Why isn't ng-src updating automatically as the model changes? I'm new to Angular, so maybe this is a concept I haven't yet grasped. Any help will be greatly appreciated.

like image 209
hawkharris Avatar asked Oct 02 '22 19:10

hawkharris


1 Answers

You are using $scope.$watch in a wrong way. Please see the documentation:

function(newValue, oldValue, scope): 
called with current and previous values as parameters.

So the function is passed the old and the new value and the scope. So if you want to make updates to your data, you will need to reference the scope. As this will equal to $scope here anyway, you can just use $scope directly and don't care for any parameter. Do this:

$scope.$watch('planet', function(){
  if ($scope.planet.name == 'pluto') {
    $scope.planet.image_url = 'images/pluto.png';
  }
});

Or if you want to use the scope passed to the function (as said, it will not make a difference at least here):

$scope.$watch('planet', function(newval, oldval, scope){
  if (newval.name == 'pluto') {
    scope.planet.image_url = 'images/pluto.png';
  }
});
like image 63
Juliane Holzt Avatar answered Oct 13 '22 12:10

Juliane Holzt