繁体   English   中英

Ng-src在AngularJS视图中不更新

[英]Ng-src doesn't update in AngularJS view

我在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的新手,所以也许这是一个我尚未掌握的概念。 任何帮助将不胜感激。

你正在使用$ 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';
  }
});

我可以通过这个有用的CodePen示例告诉我,我创建的所有东西应该可以正常工作。 看看我做了什么,让我知道如果我错过了什么。

我希望这有帮助。

模板:

<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;
      }
    }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM