我正在尝试加载具有两个不同范围变量值的图像,如下所示:
$scope.image.baseURL = "http://localhost/myApp/public/";
$scope.image.relativeURL = "app/images/template/001/section.png";
这些值是动态加载的,有时是未定义的。如果任一值未定义,则不应加载任何图像。
考虑以下示例:
<img ng-src="{{image.baseURL + image.relativeURL}}"/>
这行不通。在这种情况下,如果
relativeURL
未定义,它将解析第一个范围变量值并尝试仅使用baseURL
值访问它。由于请求http://localhost/myApp/public/
,我收到带有 400 状态代码的控制台错误。考虑以下示例:
<img src="{{image.baseURL + image.relativeURL}}"/>
这也行不通。在这种情况下,编译器在 Angular 加载之前无法解析作用域变量,因此使用带有大括号的 URL 来发出请求。由于请求
http://localhost/myApp/public/image.baseURL%20+%20image.relativeURL
,我收到控制台错误,状态代码为 400。另一个问题建议我在作用域上使用函数,如下所示:
<img ng-src="getImageUrl()"/> $scope.getImageUrl = function() { return $scope.baseURL + $scope.relativeURL}
这仍然不起作用,因为我收到了同样的错误,这次请求
<http://localhost/myApp/public/getImageUrl()
。
我可以做什么来实现这个目标?
最佳答案
ngSrc
指令有两个功能:
- 显然,核心功能很简单:WAITING Angular 加载,然后对属性值执行插值并将结果设置为
src
属性。 - 一个鲜为人知的功能是,如果任何 Angular 插值表达式的计算结果为
未定义
,则不会生成src
属性。 此行为仅出现在 1.3 及更高版本中。
因此,您使用 {{image.baseURL + image.relativeURL}}
的示例似乎可以按预期工作,但事实并非如此。为什么?
嗯,关键是为了让 Angular 表达式“短路”并被忽略,整个表达式必须计算为未定义
。如果定义了 baseURL
,但未定义 relativeURL
,则结果将只是字符串“undefined”连接到 baseURL
的末尾。显然,这个字符串不是未定义的,因此 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>
当分支未被采用时,该函数不会显式返回,因此它将计算为未定义
,并且 Angular 不会创建 src
属性。
关于javascript - 从 AngularJS 中可能为空的内插 URL 值加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32196041/