Reputation: 3545
EDIT
Issue: Want to call userdata.json
(array) via a Service, which is then called in my Controller, so the data can then be called by the View.
As it stands:
APP:
angular.module('UsersApp', []);
SERVICE:
angular.module('UsersApp').factory('UserService', function($http) {
this.getUserData = function() {
return $http.get('userdata.json');
}
})
CONTROLLER:
angular.module('UsersApp').controller('UserController', [
'UserService', // dependency on service
'$mdSidenav',
'$mdBottomSheet',
'$log',
'$timeout',
UserController // calling a function (defined below)
]);
// Declare controller as a function, then attach properties using 'this'.
//-------------------------------------------------------------------------
function UserController( UserService, $mdSidenav, $mdBottomSheet, $log, $timeout ) {
var self = this;
self.selected = null;
self.users = [];
self.selectUser = selectUser;
self.toggleList = toggleUsersList;
self.makeContact = makeContact;
// Fetch user data from UserService.js
//-------------------------------------------------------------------------
function(UserService) {
var data = UserService.getData();
};
// Internal methods
//-------------------------------------------------------------------------
// Hide or Show the 'left' sideNav area
function toggleUsersList() {
$mdSidenav('left').toggle();
}
// Select the current avatars
// @param menuId
function selectUser ( user ) {
self.selected = angular.isNumber(user) ? $scope.users[user] : user;
}
// Show the bottom sheet
//------------------------------------------------------------------------------
function makeContact(selectedUser) {
$mdBottomSheet.show({
controller : [ '$mdBottomSheet', ContactSheetController],
controllerAs : "vm",
templateUrl : './partials/contactSheet.html',
parent : angular.element(document.getElementById('content'))
})
.then(function(clickedItem) {
$log.debug( clickedItem + ' clicked!');
});
// User ContactSheet controller
//---------------------------------------------------------------------
function ContactSheetController( $mdBottomSheet ) {
this.user = selectedUser;
this.items = [
{ name: 'Phone' , icon: 'phone' , icon_url: 'svg/phone.svg'},
{ name: 'Twitter' , icon: 'twitter' , icon_url: 'svg/twitter.svg'},
{ name: 'Google+' , icon: 'google_plus' , icon_url: 'svg/google_plus.svg'},
{ name: 'Hangout' , icon: 'hangouts' , icon_url: 'svg/hangouts.svg'}
];
this.contactUser = function(action) {
// Fill in contact process here...
// then finish up with...
$mdBottomSheet.hide(action);
};
}
}
}
JSON DATA (Array):
[
{
'name': 'Lia Lugo',
'avatar': 'svg-1',
'content': 'I love cheese, especially airedale queso. Cheese and biscuits halloumi cauliflower cheese cottage cheese swiss boursin fondue caerphilly. Cow port-salut camembert de normandie macaroni cheese feta who moved my cheese babybel boursin. Red leicester roquefort boursin squirty cheese jarlsberg blue castello caerphilly chalk and cheese. Lancashire.'
},
{
'name': 'George Duke',
'avatar': 'svg-2',
'content': 'Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris.'
},
{
'name': 'Gener Delosreyes',
'avatar': 'svg-3',
'content': "Raw denim pour-over readymade Etsy Pitchfork. Four dollar toast pickled locavore bitters McSweeney's blog. Try-hard art party Shoreditch selfies. Odd Future butcher VHS, disrupt pop-up Thundercats chillwave vinyl jean shorts taxidermy master cleanse letterpress Wes Anderson mustache Helvetica. Schlitz bicycle rights chillwave irony lumberhungry Kickstarter next level sriracha typewriter Intelligentsia, migas kogi heirloom tousled. Disrupt 3 wolf moon lomo four loko. Pug mlkshk fanny pack literally hoodie bespoke, put a bird on it Marfa messenger bag kogi VHS."
}
];
Not working. Would appreciate if anyone can spot what's wrong - have tried and tried but can't figure it out.
Upvotes: 1
Views: 3535
Reputation: 56936
angular.module('app').service('UserService', function($http) {
this.getUserData = function() {
return $http.get('userdata.json')
}
})
angular.module('app').controller('MyController', function(UserService) {
var self=this;
UserService.getUserData().then(function(data) {
self.userdata = data;
console.log(self.userdata);
}).catch(function(errorResponse) {
console.log('oopsie', errorResponse);
});
}
If you are using controller as syntax this works great, if not use $scope.userdata = data
Upvotes: 3
Reputation: 2494
Just return the promise in your service method like this:
angular.module('UserApp').service('UserService', ['$http', UserService]);
function UserService($http) {
var self = this;
self.getData = function () {
return $http.get('userdata.json')
};
};
Inject this service into controller and use it like that:
angular.module('UserApp').controller('UserController', ['$scope', 'UserService', UserController]);
function UserController($scope, UserService) {
$scope.users = null;
UserService.getData()
.success(function(data) {
$scope.users = data;
})
};
Upvotes: 1
Reputation: 260
you can create a controller first from where you can add service using dependency injection like
angular.module("app").controller('controller_App',['userService',function(userService)
{
var data= userService.getData();
}]);
In the service you can use $http dependency like this
angular.module("app").service("userService",['$http',function($http){
$http({url:'https://www.any_link.com'}).then(function(successResponse){
return successResponse;
},function(errorResponse){
return errorResponse
});
}
}]);
Upvotes: 1
Reputation: 7215
You need to return the data in your promise in the service, don't assign it to scope.
Then in controller you would just call your service function and assign the result of that, which will be the data to a scope variable in the controller.
Upvotes: 2