Donn Felker
Donn Felker

Reputation: 9651

Getting a value from a AngularJS Promise in MeanJS

I'm playing around with MeanJS recently and I ran into an issue that I'm not well versed in so I'm hoping someone can help here.

I have a angular controller that sets it scope like this:

// Find existing Topic
$scope.findOne = function() {
    $scope.topic = Topics.get({
        topicId: $stateParams.topicId
    });
};

I this sets the topic in the $scope. However, I also need to get a value off of the topic as well. Lets assume it is a date such as createdAt. I need to get this value and then perform another operation on it in order to set another scope value. The problem is, the $scope.topic object is an Angular promise. How can I get the value createdAt (which is a Date) off of that promise?

Upvotes: 1

Views: 184

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

You can use promise callback.

$scope.findOne = function() {
    $scope.topic = Topics.get({
        topicId: $stateParams.topicId
    });
    $scope.topic.$promise.then(function(data) {
        // access data.createdAt here
    });
};

Its actual also depends on that where you want to use this. So if you want to use this in the view, you can write directly as:

<span> Created at: {{topic.createdAt}}</span>

Angular will autoupdate that scope variable when data is loaded.

Upvotes: 2

Related Questions