在AngularJS中从可能为空的插值URL值加载图像

Load image from potentially-null interpolated URL values in AngularJS

本文关键字:插值 URL 图像 加载 AngularJS      更新时间:2023-09-26

我正在尝试用两个不同的范围变量值加载图像,如下所示:

$scope.image.baseURL = "http://localhost/myApp/public/";
$scope.image.relativeURL = "app/images/template/001/section.png";

这些值是动态加载的,有时是未定义的。如果两个值都未定义,则不应加载任何图像。

  1. 考虑以下示例:

    <img ng-src="{{image.baseURL + image.relativeURL}}"/>
    

    这行不通。在本例中,如果relativeURL未定义,则解析第一个作用域变量值,并尝试仅使用baseURL值访问它。由于请求http://localhost/myApp/public/,我得到一个带有400状态码的控制台错误。

  2. 考虑以下示例:

    <img src="{{image.baseURL + image.relativeURL}}"/>
    

    这也不行。在这种情况下,编译器在Angular加载之前无法解析作用域变量,所以用花括号括起来的URL来发出请求。由于请求http://localhost/myApp/public/image.baseURL%20+%20image.relativeURL,我得到一个带有400状态码的控制台错误。

  3. 另一个问题建议我在作用域上使用函数,像这样:

    <img ng-src="getImageUrl()"/>
    $scope.getImageUrl = function() { return $scope.baseURL + $scope.relativeURL}
    

    这仍然不工作,因为我得到一个相同的错误,这一次与请求http://localhost/myApp/public/getImageUrl()

我能做些什么来实现这一点?

ngSrc指令有两个功能:

    显然,核心功能很简单:它等待Angular加载,然后对属性值执行插值,并将src属性设置为结果。
  1. 一个不太为人所知的特性是,如果任何角插值表达式求值为undefined,则不会生成src属性。此行为仅在1.3及更高版本中存在。
因此,它会看起来,你的例子使用{{image.baseURL + image.relativeURL}}将按预期工作,但它不是。为什么?

好吧,关键是为了使角度表达式"短路"并被忽略,整个表达式必须求值为undefined。如果baseURL被定义,但relativeURL没有定义,结果将是字符串"undefined"连接到baseURL的末尾。显然,这个字符串不是 undefined,所以Angular会渲染src属性。

幸运的是,这很容易修复:只需使用两个表达式,而不是在表达式中进行字符串连接。

angular.module('Sample', [])
  .controller('SampleController', ['$scope', function ($scope) {
    $scope.image = {
      baseURL: 'https://example.com/',
      relativeURL: undefined
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.js"></script>
<div ng-app="Sample" ng-controller="SampleController">
  <img ng-src="{{image.baseURL}}{{image.relativeURL}}">
</div>

注意没有创建src属性!

然而,有时候,你需要在Angular表达式中执行的处理量确实太重了。在这种情况下,您可以使用函数,但是为了利用这种行为,如果您不希望出现任何src属性,则必须返回undefined

angular.module('Sample', [])
  .controller('SampleController', ['$scope', function ($scope) {
    var image = {
      baseURL: 'https://example.com/',
      relativeURL: undefined
    };
    $scope.fullUrl = function () {
      if (image.baseURL && image.relativeURL) {
        return image.baseURL + image.relativeURL;
      }
    };
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.js"></script>
<div ng-app="Sample" ng-controller="SampleController">
  <img ng-src="{{fullUrl()}}">
</div>

当分支没有被接受时,该函数不会显式返回,所以它的求值为undefined, Angular不会创建src属性。

检查工作演示:JSFiddle.

在ngSrc文档中:

ngSrc模板任何可以包含{{}}标记的字符串。

angular.module('Joy', [])
.controller('JoyCtrl', ['$scope', function ($scope) {
    $scope.base = 'https://www.google.com.hk/images/srpr/';
    $scope.image = 'logo11w.png';
    $scope.getImageUrl = function () {
        return $scope.base + $scope.image;
    };
}]);
HTML:

<div ng-app="Joy" ng-controller="JoyCtrl">
    <img ng-src="{{getImageUrl()}}"/>
</div>