每次添加角度对象时,我都会尝试生成随机图像。在我的HTML中,我说:
<img ng-src="{{posts.img}}">
然而,在url字段中它正在返回
%7B%22url%22:%22https://i.pinimg.com/originals/23/4f/2f/234f2fe11f1a71b058ab19d9a3d0801a.jpg%22%7D
而不仅仅是图片网址。我做错了什么?
这是我的js:
$scope.addPost = function() {
var url;
var num = Math.floor(Math.random() * 3) + 1;
if (num === 1) url = "https://uproxx.files.wordpress.com/2013/05/creedbratton-creedthoughts-1.gif?w=650";
else if (num === 2) url = "https://i.imgur.com/90akEXq.gif";
else if (num === 3) url = "https://i.pinimg.com/originals/23/4f/2f/234f2fe11f1a71b058ab19d9a3d0801a.jpg";
$scope.posts.push({
title:$scope.formContent,
upvotes:0,
comments:[],
img:{url} //this is what I'm having trouble with
});
答案 0 :(得分:0)
更改为:
$scope.posts.push({
title:$scope.formContent,
upvotes:0,
comments:[],
img:url //this is what I'm having trouble with
});
答案 1 :(得分:0)
你有正确的想法但是在你的HTML中我假设你试图迭代你的帖子,但看起来你正在直接从数组中访问一个属性。
现在你有:
<img ng-src="{{posts.img}}">
不应该访问数组的元素吗?例如:
<img ng-src="{{posts[0].img}}">
此外,您正在将具有url属性的对象推送到img属性中。你有:
$scope.posts.push({
title:$scope.formContent,
upvotes:0,
comments:[],
img:{url} <-----
});
但实际上你不应该将它包装在{}
(删除{})
$scope.posts.push({
title:$scope.formContent,
upvotes:0,
comments:[],
img:url <-----
});
答案 2 :(得分:0)
您有一个变量url
,并且您要通过$scope.post
将其添加到img:{url}
对象。但实际上,您正在向{url: urlValue}
键添加对象img
。
您需要修改img
密钥的值img:url
。然后,您的代码将是
$scope.posts.push({
title:$scope.formContent,
upvotes:0,
comments:[],
img:url
});
然后,您可以使用<img ng-src="{{posts.img}}">
如果您仍想将图片网址存储在对象中。
$scope.posts.push({
title:$scope.formContent,
upvotes:0,
comments:[],
img:{url}
});
然后您可以访问图片网址<img ng-src="{{posts.img.url}}">
答案 3 :(得分:0)
假设在你的HTML中,你有一个拼写错误,代码应该是这样的:
<img ng-src="{{posts[0].img}}">
问题在于这段代码:
img:{url}
{url}
是EcmaScript shorthand property synatax,它在所有现代浏览器中都有效。由于这种行为,代码变成这样:
img: {
url: 'https://i.imgur.com/90akEXq.gif'
}
在您的代码中,您指的是img
中的密钥ng-src
,其实际字符串化和URL编码:
{
url: 'https://i.imgur.com/90akEXq.gif'
}
到此:
%7Burl:%20'https://i.imgur.com/90akEXq.gif'%7D
// encodeURI(JSON.stringify(posts[0].img));
因此,您在HTML中看到了这个格式错误的字符串。要解决此问题,您需要将HTML更改为:
<!-- img.url returns the URL string, instead of the object -->
<img ng-src="{{posts[0].img.url}}">