Ng-src在AngularJS视图中不更新

时间:2013-10-01 22:22:57

标签: javascript dom angularjs

我在Angular应用程序中使用以下代码来显示图像:

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

我正在使用$watch在其他事件发生时更改image_url属性。例如:

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

使用控制台日志,我看到模型属性正在改变,就像我想要的那样,但这些更改不会反映在DOM中。为什么ng-src在模型更改时不会自动更新?我是Angular的新手,所以也许这是一个我尚未掌握的概念。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

你正在使用$ scope。$以错误的方式观看。请参阅文档:

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

因此函数传递旧值和新值以及范围。因此,如果要更新数据,则需要引用范围。因为这将等于$ scope,你可以直接使用$ scope而不关心任何参数。这样做:

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

或者如果你想使用传递给函数的范围(如上所述,它至少在这里不会产生任何影响):

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

答案 1 :(得分:2)

我可以通过this working CodePen example告诉我,我创造的一切都应该可以正常工作。看看我做了什么,让我知道如果我错过了什么。

我希望这会有所帮助。

模板:

<section class="well" ng-app="app" ng-controller="MainCtrl">
  Select Planet:<br>
  <label>Earth <input type="radio" ng-model="planetId" value="1" /></label>
  <label>Mars <input type="radio" ng-model="planetId" value="2" /></label>

  <img ng-src="{{currentPlanet.url}}" />
  <span class="label">{{currentPlanet.label}}</span>
</section>

代码:

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

app.controller('MainCtrl', function($scope) {
  $scope.currentPlanet = {};

  $scope.planets = [{
    id: 1,
    label: 'Earth',
    url: 'http://s10.postimg.org/uyggrc14l/earth.png'
  },{
    id: 2,
    label: 'Mars',
    url: 'http://s21.postimg.org/maarztjoz/mars.png'
  }];

  $scope.$watch('planetId', function(id) {
    for(var i = 0; i < $scope.planets.length; i++) {
      var planet = $scope.planets[i];
      if(planet.id == id) {
        $scope.currentPlanet = planet;
        break;
      }
    }
  });
});