angularjs-在ng-src中使用{{}}绑定,但是ng-src无法加载 [英] angularjs - using {{}} binding inside ng-src but ng-src doesn't load

查看:413
本文介绍了angularjs-在ng-src中使用{{}}绑定,但是ng-src无法加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将值绑定到img HTML元素的ng-src无济于事.

I have been trying to bind a value to the ng-src of an img HTML element to no avail.

HTML代码:

<div ng-controller='footerCtrl'>
<a href="#"><img ng-src="{{avatar_url}}"/></a>
</div>

AngularJS代码:

AngularJS code:

app.controller('footerCtrl',function($scope, userServices)
{
$scope.avatar_url='';
$scope.$on('updateAvatar', function()
{$scope.avatar_url = userServices.getAvatar_url();}
);
}

app.factory('userServices', function($rootScope){ 
var avatar_url='';
return{  setAvatar_url: function(newAvatar_url)
{ avatar_url = newAvatar_url; $rootScope.$broadcast('updateAvatar');}}
);

我想每次更新用户服务中相应变量(avatar_url)时都更新ng-src中的avatar_url变量.用户服务中的变量通过对服务器的http.POST请求进行更新.我检查了服务器的响应是否确实更新了用户服务中的变量,然后将该变量广播到footerCtrl中的avatar_url变量.

I would like to update the avatar_url variable in the ng-src every-time its respective variable(avatar_url) in the user Service is updated. The variable in the user Service is updated through a http.POST request to the server. I have checked that the response from the server does update the variable in the user Service which is then broadcast to the avatar_url variable in the footerCtrl.

但是,图像元素HTML根本不反映更改.实际上,我还尝试将avatar_url变量预设为页面中图片之一的相对路径,该图片仍然不显示任何内容(ng- src值为空). T

However, the image element HTML does not reflect the changes at all. In fact, I have also tried to preset the avatar_url variable to a relative path to one of the pictures in my page, the image still shows nothing(the ng-src value is empty). T

推荐答案

更改ng-src值实际上非常简单.像这样:

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

这是一个工作示例的jsFiddle: http://jsfiddle.net/Hx7B9/2/

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

这篇关于angularjs-在ng-src中使用{{}}绑定,但是ng-src无法加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆