I have controller, view and services in separate files of an Angular application. These files are:
home.controller.js
angular
.module('loc8rApp')
.controller('homeCtrl', homeCtrl);
function homeCtrl () {
var vm = this;
vm.pageHeader = {
title: 'Loc8r',
strapline: 'Find places to work with wifi near you'
};
}
home.view.html
<div id="banner" class="page-header">
<div class="row">
<div class="col-lg-6"></div>
<h1>
{{ vm.pageHeader.title }}
<small>{{ vm.pageHeader.strapline }}</small>
</h1>
</div>
</div>
loc8rData.service.js
angular
.module('loc8rApp')
.service('loc8rData', loc8rData);
var loc8rData = function ($http) {
var locationByCoords = function (lat, lng) {
return $http.get('/api/locations?lng=' + lng + '&lat=' + lat + '&maxDistance=10000');
};
return {
locationByCoords: locationByCoords
};
};
The application with home.controller.js and home.view.html is ok. Now I want to use the service loc8rData which is defined in loc8rData.service.js file. To use the service from the controller, I passed the service name as a parameter of homeCtrl function. It then created an issue. It is showing angular expression instead of the value of that expression. The following image is the best fit to observe the issue:
What is the reason behind it? What will be the proper solution?
You need to inject your service to your controller as follows,
homeCtrl.$inject = ['loc8rData'];
function homeCtrl (loc8rData) {
}
also change your service function as follows , make it globally accessible
angular
.module('loc8rApp')
.service('loc8rData', loc8rData);
function loc8rData($http) {
var locationByCoords = function (lat, lng) {
return $http.get('/api/locations?lng=' + lng + '&lat=' + lat + '&maxDistance=10000');
};
return {
locationByCoords: locationByCoords
};
};