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?
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');
}
};
}]);