这里我试图返回我收到的每个id的url,但是url是异步生成的,因此需要花时间生成并且我无法将其放入视图中。如何让它等到从PouchDB获取数据并生成Url
控制器
$scope.getColour = function(id) {
var texture_array = [];
texture_array = photoList.data.economy.concat(photoList.data.luxury, photoList.data.premium);
var db = PouchDB('new_test4');
var obj = {};
var array = [];
var i;
// console.log(texture_array.length)
for (i = 0; i < texture_array.length; i++) {
//var id = texture_array[i].image_url;
if (texture_array[i].image_url == id) {
db.getAttachment(id, id, function(err, blob_buffer) {
if (err) {
return console.log(err);
} else {
var url = URL.createObjectURL(blob_buffer);
console.log(url);
return url;
}
});
}
}
};
HTML
<div class="item" ng-repeat="photoOuterObj in remainingEconomyColour " ng-class=" $index? '' : 'active'">
<div class="row" ng-repeat="photoInnerObj in photoOuterObj">
<div class="premium-carousel-image">
<a class="color-image"> <img src="{{getColour(photoInnerObj.image_url)}}" alt="Image" /></a>
<div class="ambience-button">
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
转换getColor
函数以返回承诺:
$scope.getColourPromise = function(id) {
var texture_array = [];
texture_array = photoList.data.economy.concat(photoList.data.luxury, photoList.data.premium);
var db = PouchDB('new_test4');
var obj = {};
var array = [];
var i;
//Create deferred object
var defer = $q.defer();
// console.log(texture_array.length)
for (i = 0; i < texture_array.length; i++) {
//var id = texture_array[i].image_url;
if (texture_array[i].image_url == id) {
db.getAttachment(id, id, function handler(err, blob_buffer) {
if (err) {
//return console.log(err);
//reject on error
defer.reject("db ERROR "+err);
} else {
var url = URL.createObjectURL(blob_buffer);
console.log(url);
//resolve with url;
defer.resolve(url);
}
});
}
}
//return promise
return defer.promise;
};
由于getAttachment
方法在getHandler
函数完成后异步执行getColour
函数,因此无法返回值,但它可以解决延迟对象。
使用ng-init
获取网址并将其附加到ng-repeat
迭代器对象:
<div class="row" ng-repeat="innerObj in photoOuterObj">
<!-- use ng-init to do the fetch -->
<div ng-init="innerObj.urlObj = fetchURL(innerObj)">
<a class="color-image"> <img ng-src="{{innerObj.urlObj.url}}" alt="Image" /></a>
<div class="ambience-button">
</div>
</div>
</div>
获取功能:
$scope.fetchURL = function(itemObj) {
var urlObj = {};
urlObj.url = "default.jpg";
var promise = $scope.getColourPromise(itemObj.image_url);
promise.then(function (url) {
urlObj.url = url;
});
return urlObj;
});
fetch最初返回一个url
属性设置为默认值的对象。当promise解析时,它将被设置为获取的值。观察者创建了双花括号{{ }}
表达式将更新DOM。
避免在插值{{ }}
中使用异步函数,因为它们在每个摘要周期被调用多次。