Reputation: 1722
I have an angular factory and controller as such:
angular.module('myApp', ['ui.router', 'ngResource'])
.factory('Widget', ['$http', function WidgetFactory($http) {
return {
all: function() {
return $http({method: "GET", url: "/widgets"});
}
};
}])
.controller('StoreCtrl', ['$scope', 'Widget', function($scope, Widget) {
$scope.widgets = Widget.all();
}]);
In my front-end I have
<div ng-controller="StoreCtrl">
<li ng-repeat="widget in widgets">
{{ widget.price }}
{{ widget.name }}
</li>
</div>
But nothing gets populated in my {{ widget.price }}
and etc.
What am I missing?
Upvotes: 0
Views: 1145
Reputation: 16989
You are not quite resolving your promise as the framework expects. Check out the $q docs for some explanation on promises. We also need to set our view model value (scope) to the correct returned value from the response object, composed of the following...
- data – {string|Object} – The response body transformed with the
- transform functions. status – {number} – HTTP status code of the
- response. headers – {function([headerName])} – Header getter function.
- config – {Object} – The configuration object that was used to generate
- the request. statusText – {string} – HTTP status text of the response.
Observe the following...
Widget.all().then(function (response) {
$scope.widgets = response.data;
});
Furthermore, as a few observations, there is no need to name your factory function as you did with WidgetFactory
, an anonymous function will do. You can also leverage the $http shortcut method get
as well as such...
.factory('Widget', ['$http', function($http) {
return {
all: function() {
return $http.get('/widgets');
}
};
}]);
Upvotes: 3
Reputation: 731
First make sure you have an objects of Array at
$scope.widgets;
in your controller. you can print this line in your controller
console.log($scope.widgets);
to see if the data is available or not.
Upvotes: 0
Reputation: 662
$http returns a promise. You need to assign the response data to $scope.widgets when the promise resolves. In the controller, try this:
Widget.all().then(function (data) {
$scope.widgets = data;
});
Upvotes: 2