I wrote a controller containing this function:
$scope.getItemName = function (id) {
sgcdata.get('item', {
_id: id
}).then(function (dataItem) {
return dataItem[0].brand_name + " " + dataItem[0].reference;
});
}
And in the view:
<li ng-repeat="itemCart in connectedUser.cart track by $index" class="list-group-item">
<span class="badge cursorpointer" ng-click="removeFromCart(itemCart)">X</span>
<a href="#">{{ getItemName(itemCart) }}</a>
</li>
When I do this, I get an infinite loop ($rootScope:infdig
).
sgcdata.get
make an XHR request.
But if I return a simple string, it works:
$scope.getItemName = function (id) {
return "toto";
}
I really don't understand what is happening...
Thanks for your help.
Edit
I made a filter instead of the previous function:
JS:
sgc.filter('getItemName', [
'sgcdata',
function (sgcdata) {
return function (id) {
sgcdata.get('item', {
_id: id
}).then(function (dataItem) {
return dataItem[0].brand_name + " " + dataItem[0].reference;
});
}
}
]);
HTML:
<li ng-repeat="itemCart in connectedUser.cart track by $index" class="list-group-item">
<span class="badge cursorpointer" ng-click="removeFromCart(itemCart)">X</span>
<a href="#">{{ itemCart | getItemName }}</a>
</li>
I don't have any infinite loop anymore, but I can't get several values in the ng-repeat, while the filter return is in the item request.
Edit
sgcdata.get:
service.get = function (collection, filters) {
var deferred = $q.defer();
var formatRequest = function (obj) {
var str = [];
for (var p in obj) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
if (str.length) {
return '&' + str.join('&');
} else {
return '';
}
};
$http({
method: 'GET',
url: '/v1/get/?element=' + collection.toLowerCase() + formatRequest(filters)
}).then(function (response) {
deferred.resolve(response.data);
}, function (response) {
console.error("[ FAILED ] >> " + response);
});
return deferred.promise;
}
sgcdata
a Promise ($q
/$http
)?$http
already returns a promise, there is no need to use$q
, that's an anti-pattern.