Angular JS - service not working - angularjs

I am using a service to get data from the server using $http.get() method. I am calling the function in the service and then accessing its variable from the controller. But it is not working this way.
The code is below
'use strict';
var mission_vision_mod = angular.module('myApp.mission_vision', ['ngRoute']);
mission_vision_mod.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/mission_vision', {
templateUrl: 'partials/mission_vision/mission_vision.html',
controller: 'mission_visionCtrl'
});
}]);
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope, $http, getMissionData) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getmissiondata();
$scope.missions = getMissionData.missiondata;
$scope.len = $scope.missions.length;
}]);
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
});
}
}]);
When i write the$http.get() function in the controller itself, it works. I am new to angular JS.

Try writing your service like this
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
this.getMissionData=function(){
return $http.get('m_id.json');
}
}]);
Use Service in controller like this:
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope,getMissionData,$http) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getMissionData().success(function(response){
$scope.missions=response;
$scope.len = $scope.missions.length;
}).error(function(errorl){
//handle error here
});
}]);
Also I suggest using a better name for service -'MissionDataService' :)
EDIT- Your sequence of injected service should match sequence of injectable names specified in the array..See my last edit

['$scope','getMissionData','$http',
function($scope, $http, getMissionData
The service names don't match with the variable names.
My advice: stop using this array notation. It clutters the code and is a frequent source of bugs. Use ng-annotate.
That said, your service is not correctly defined. It doesn't have any member function that would allow it to be called. Re-read the documentation of services. Defining services using factory() is easier than defining them using service(), BTW. And the service should return the promise returned by $http. Trying to access the value returned by an asynchronous call right after making the asynchronous call will never work. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/

Try:
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
return missiondata;
});
}
}]);

Related

Can't call on a function in $scope from inside the $http service in the same controller

I was trying to move one of the function I had in my JS file to inside my Angular controller, since I'm calling on this function from inside the controller and it makes sense to put it there and not go to another file.
I can't seem to make the $http service know of this function (highlighter1)
(function(angular) {
'use strict';
angular.module('myApp', ['ui.bootstrap'])
.controller('Controller', function($scope, $http) {
$scope.highLighter1 = function(side, string, load, callback) {}
$http.get('/comments')
.success(function(response) {
$scope.comments = response;
var allEl=[];
var i;
for (i=0; i<response.length; i++) {
allEl.push(response[i]._id);
}
$http.post('/ranges', {"commentIds":allEl})
.success(function(result){
result.forEach(function(item){
highlighter1(item.dataAction, item.rangyObject, true);
})
})
});
})
})(window.angular);
I'm getting an error in the console that "can't file variable highlighter1", so I'm guessing that I need to somehow register it in a different scope of something like that?
It's not a global or even local function. It's an attribute of $scope. So you need $scope.highLighter1(...).
Also note the capital L. JavaScript is case-sensitive.

Conditionally inject angular module dependency

I'm new to angular and have the following code.
angular.module('MyApp')
.controller('loginController', ['$scope', '$http', 'conditionalDependency',
function ($scope, $http, conditionalDependency{
}
I would like to have conditionalDependency loaded conditionally. Something like this
if(true)
{
//add conditionalDependency
}
How can this be done. I've seen this post . However, my requirement is that I have the dependency specified in function
Thanks in advance.
Not quite clear as to why you would have to have it in a named function like in your example but...
If you need conditional dependencies, I would suggest taking a look at the following:
Conditional injection of a service in AngularJS
I've used this method in a couple niche scenarios and it works quite well.
EXAMPLE:
angular.module('myApp').controller('loginController',
['$injector', '$scope', '$http',
function($injector, $scope, $http) {
var service;
if (something) {
service = $injector.get('myService');
}
});
You can use it even without injecting injector in your controller
if(something){
var injector = angular.element(document).injector();
var myService = injector.get('myService')
}
Use:
angular.injector().get('conditionalDep');
You can inject $injector once to your file and call $injector.get('dep');

Angular.JS share a single JSON object between controllers

I´m trying to code a CRUD app with Angular.JS, and I need your help to move on.
This is the scenario:
View 1 (index) gets JSONP data from a remote API and stores it.
View 2 (master) shows data filtered on a grid
View 3 (detail) shows an specific item selected on View 2
I did it already, but requesting the very same JSON object on each view, , but I think one only api call is enough.
I can´t figure out how to properly share this JSON object for all the controllers. I tried several tutorials on ngResource, $http, factories and services but still have not a clear path to go through.
How can I do this?
Any snippet or code sample you may share will be very useful to keep on tryin this thing...
Thanks in advance,
Ariel
You can implement a base controller to store common functionality that's shared between the controllers. I wrote a blog post about it recently, here's the code snippet showing how it works:
'use strict';
angular.module('Diary')
// base controller containing common functions for add/edit controllers
.controller('Diary.BaseAddEditController',
['$scope', 'DiaryService',
function ($scope, DiaryService) {
$scope.diaryEntry = {};
$scope.saveDiaryEntry = function () {
DiaryService.SaveDiaryEntry($scope.diaryEntry);
};
// add any other shared functionality here.
}])
.controller('Diary.AddDiaryController',
['$scope', '$controller',
function ($scope, $controller) {
// instantiate base controller
$controller('Diary.BaseAddEditController', { $scope: $scope });
}])
.controller('Diary.EditDiaryController',
['$scope', '$routeParams', 'DiaryService', '$controller',
function ($scope, $routeParams, DiaryService, $controller) {
// instantiate base controller
$controller('Diary.BaseAddEditController', { $scope: $scope });
DiaryService.GetDiaryEntry($routeParams.id).success(function (data) {
$scope.diaryEntry = data;
});
}]);
Using services to cache and share the data across controllers would be the way to go. Since services in angular are singleton, the same copy of data can be shared. A service such as
angular.module('myApp').factory('dataService', function($q, $resource) {
var items=[];
var service={};
service.getItems=function() {
var itemsDefer=$q.defer();
if(items.length >0)
itemsDefer.resolve(data);
else
{
$resource(url).query({},function(data) {
items=data;
itemsDefer.resolve(data)
});
}
return itemsDefer.promise;
}
return service;
});
Now in the controller you can inject the dataService and call the getItems method. This method returns a promise, which is either resolved using the cached data or by making remote request.
And the controller code would look something like
angular.module('myApp').controller('MyCtrl', function($scope,dataService) {
dataService.getItems().then(function(items) {
$scope.items=items;
}
});

Injecting a service into another service in angularJS

Is it possible to inject one service into another service in angularJS?
Yes. follow the regular injection rule in angularjs.
app.service('service1', function(){});
//Inject service1 into service2
app.service('service2',function(service1){});
Thanks to #simon. It is better to use Array injection to avoid minifying problem.
app.service('service2',['service1', function(service1) {}]);
Yes. Like this (this is a provider, but same thing applies)
module.provider('SomeService', function () {
this.$get = ['$q','$db','$rootScope', '$timeout',
function($q,$db,$rootScope, $timeout) {
return reval;
}
});
In this example, $db is a service declared elsewhere in the app and
injected into the provider's $get function.
In order to avoid any confusion, I think it is also worth mentioning that if you are using any other services (e.g. $http, $cookies, $state) in your childService, then you also need to explicitly declare them.
e.g.
function() {
var childService = function($http, $cookies, parentService) {
// Methods inherited
this.method1Inherited = parentService.method1();
this.method2Inherited = parentService.method2();
// You can always add more functionality to your child service
angular.module("app").service("childService", ["$http", "$cookies", "parentService", childService]);
}());
You can either declare the services you are using inside your child in an array and then they get injected automatically, or inject them separately with the $inject annotation:
childService.$inject = ["$http", "$cookies", "parentService"];
angular.module("app").service("childService ", childService );

Getting $Scope in angular.module.controller

This is a noobie question:
I am playing with the Angular seed app and am trying to write a controller but am having no luck getting access to $scope (and any other dependency).
angular.module('myApp.controllers', []).
controller('mainCtrl', [function( $scope, $http ) {
$http.get('config/configuration.json').success( function( data ) {
$scope.gametitles = data.gametitles;
$scope.environments = data.environments;
$scope.playermanagerServer = data.playermanagerServer;
});
$scope.gametitle = $scope.gametitles[0];
$scope.environment = $scope.environments[0];
}])
If I break in the code, both $http and $scope are undefined. How do I get access to these?
Thanks in advance
I think the problem is in the syntax of your controller declaration. Try controller('mainCtrl', ['$scope', '$http', function ($scope, $http) { ... controller code ...}]);
you may want to check A's documentation for dependency injection in controllers here
Or,assuming you're not uglifying your code you could just use simpler injection formation:
controller('mainCtrl', function( $scope, $http ) {} )
(note that the function is not a member of an array, but passed directly)

Resources