【问题标题】:Ng-src doesn't update in AngularJS viewNg-src 不会在 AngularJS 视图中更新
【发布时间】:2013-10-08 06:02:44
【问题描述】:

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

【问题讨论】:

  • 默认的 planet.image_url 是什么?如果与“images/pluto.png”相同,则可能需要使用缓存破坏器。

标签: javascript dom angularjs


【解决方案1】:

您以错误的方式使用 $scope.$watch。请参阅文档:

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

【讨论】:

    【解决方案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;
          }
        }
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多