gpt4 book ai didi

angularjs - Angular : How to load images through XHR request in ng-repeat loop

转载 作者:行者123 更新时间:2023-12-01 14:16:13 24 4
gpt4 key购买 nike

我正在尝试创建一个联系人簿,每个人都可以在其中拥有一张照片。因为我想在获取照片之前显示联系人,所以我会写类似的内容

<ul>
<li ng-repeat="person in persons">{{person.firstname}} {{persone.lastname}}</li>
</ul>

我会尝试调用在我的范围内可用的 get_photo(person)。

<ul>
<li ng-repeat="person in persons">{{person.firstname}} {{persone.lastname}}
<img ng-src="{{get_photo(person)}}" />
</li>
</ul>

这不起作用,因为它将函数绑定(bind)到 ng-src 并在每次调用 ng-repeat 时调用 get_photo。

我终于尝试在初始化DOM元素时调用get_photo并将结果存储在特定属性photo

<ul>
<li ng-repeat="person in persons">{{person.firstname}} {{persone.lastname}}
<img ng-init="get_photo(person)" ng-src="{{person.photo}}" />
</li>
</ul>

$scope.get_photo = function (person) {
// Simple example; I will try to get an image through xhr request later...
person.photo = "http://img.blogduwebdesign.com/benjamin-sanchez/737/AngularJS.jpg";
};

有没有更简单/更简洁的方法来做同样的事情?我还创建了一个 jsFiddle:http://jsfiddle.net/V4Mss/

非常感谢您的反馈!

t00f

最佳答案

你的最后一个例子看起来不错,但这里有另一个选项可以让 View 更干净一点,并且不会导致双重 $digest。从每个元素中删除初始化函数并将该函数用作 getter。

HTML

<img ng-src="{{person.photo}}" />

JavaScript

myapp.controller('controller', function ($scope) {
$scope.count = 0;
$scope.get_photo = function (person) {
return "http://img.blogduwebdesign.com/benjamin-sanchez/737/AngularJS.jpg";
};
$scope.persons = [{firstname:"toto", lastname:"TOTO", photo:$scope.get_photo()},
{firstname:"tata", lastname:"TATA", photo:$scope.get_photo()},
{firstname:"titi", lastname:"TITI", photo:$scope.get_photo()}];

});

Here is a fiddle

关于angularjs - Angular : How to load images through XHR request in ng-repeat loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com