How do I bind the array (conversations) to ng-repeat within the controller below. I've tried binding it in a function, the intent is for this to run when the controller loads up and then bind the data to the view.
Any help appreciated.
.factory('UserMessages', function ($q, $http) {
var conversations = [];
return {
getMessages: function () {
var userdata = JSON.parse(localStorage.getItem("userdata")), userID = userdata.ID;
$http.get('api/Messages/GetUserConversations?id=' + userID)
.then(function (data) {
conversations = data.data;
return conversations;
})
}
}
})
The controller:
.controller('MessagingCtrl', function ($scope, $http, UserMessages, $stateParams, TruckersOnlyUrl) {
console.log('MessagingCtrl loaded.');
UserMessages.getMessages();
});
This isn't a syntax issue as the data is being returned and I've logged it in the console successfully, I just can't figure out how to render it to the view.
I've tried:
$scope.msgs = UsersMessages.getMessages();
but no luck.
UPDATE- ANSWER
UserMessages.getMessages().then(function (conversations) {
$scope.conversations = conversations;
});
.factory('UserMessages', function ($q, $http) {
var getMessages = function () {
var deferred = $q.defer();
var userdata = JSON.parse(localStorage.getItem("userdata")), userID = userdata.ID;
$http.get('api/Messages/GetUserConversations?id=' + userID)
.then(function (data) {
deferred.resolve(data.data);
})
return deferred.promise;
};
return {
getMessages: getMessages
};
});
You need to return the promise from the $http call in the service, and in your controller add a.then handler to the service method call. In the then handler update your scope property FTW