losing scope data outside $http service - angularjs

I'm new in angularjs and i have a problem trying to use $scope inside a $http.
inside $http i can see data but outside service i get null.
Console.log($scope.data) inside service I get data:
Console.log($scope.data) outside always null:
mycode :
(function (app, ng) {
'use strict';
app.controller('mainController', ['$scope', 'ServicePatient', function ($scope, ServicePatient) {
$scope.data = null;
ServicePatient.all().success(function (data) {
$scope.data = data;
});
$scope.sortType = 'last_Name'; // the default sort type
$scope.sortReverse = false; // the default sort order
$scope.search = ''; // the default search/filter term
$scope.filterEnabled = '';
$scope.setEnabled = function(status){
$scope.filterEnabled = status;
if(status){
angular.element(document.querySelector( '#enabledFalse')).removeClass('active-btn');
angular.element(document.querySelector( '#enabledTrue')).addClass('active-btn');
} else {
angular.element(document.querySelector( '#enabledTrue')).removeClass('active-btn');
angular.element(document.querySelector( '#enabledFalse')).addClass('active-btn');
}
}
console.log($scope.data);
}]);
app.service('ServicePatient', ['$http', function ($http) {
function all() {
return $http({
url: 'http://54.165.192.65/ekare/ws6.php?request=patient',
method: 'GET'
});
}
return {
all: all
}
}]);
}(angular.module('app', []), angular));

Related

Callback when entity returns data

How to call callback when Device returns data and pass this to the callback method.
Controller
(function() {
'use strict';
angular
.module('frontendApp')
.controller('DeviceController', DeviceController);
DeviceController.$inject = ['$scope', '$state', 'Device'];
function DeviceController ($scope, $state, Device) {
var vm = this;
vm.devices = [];
loadAll();
function updateMap(flag){
var self = this;//how to pass "this" from loadAll()?
// logic to update map
}
function loadAll() {
Device.query(function(result) {
vm.devices = result;
// Callback function here - updateMap(true)
});
}
}
})();
Service
function Device ($resource, DateUtils) {
var resourceUrl = 'api/devices/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'update': { method:'PUT' }
});
}
As discussed, you can use vm directly inside the updateMap function as below.
(function() {
'use strict';
angular
.module('frontendApp')
.controller('DeviceController', DeviceController);
DeviceController.$inject = ['$scope', '$state', 'Device'];
function DeviceController ($scope, $state, Device) {
var vm = this;
vm.devices = [];
loadAll();
function updateMap(flag){
console.log(vm.devices);
}
function loadAll() {
Device.query(function(result) {
vm.devices = result;
// Callback function here - updateMap(true)
});
}
}
})();

writing a simple Angular Service

OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:
app.js:
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = [];
function dataService() {
console.log("I am the dataService and I am loaded");
var foo = 1;
function getData () {
return 2;
}
}
})();
I see this on-screen: I am Angular and I am working. so Angular is loading.
I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.
But then the console.log is:
undefined (line 8)
TypeError: dataService.getData is not a function (line 9)
What am I missing?
The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:
function dataService() {
var dataService = this; //get a reference to the service
//attach your functions and variables to the service reference
dataService.foo = 1;
dataService.getData = function() {
return 2;
};
}
An Angular service is very simply an object class. It is also a singleton, meaning it's instantiated only once per run of your app. When the service is instantiated it is very much akin to calling the new operator on your dataService "class":
var $dataService = new dataService();
So, when you inject dataService into your controller, you are actually getting an instance, $dataService, of your dataService "class".
See this blog entry for further reading: https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.sneoo52nk
You are missing the 2nd parameter $http in the function. The named parameters and the actual parameters in function need to be the same, same order and same number. What happened before is that dataService was being assigned an $http instance and the actual dataService was not injected at all because there was no 3rd parameter to inject it into.
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, $http, dataService) {
// ----was missing-----^
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
We have missed the second param '$http' in function. Just add the '$http' param, it should work fine
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope,$http, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
This is how I've been taught to set up services:
function dataService() {
var dataService = {};
var _foo = 1;
var _getData = function () { return 2; }
dataService.foo = _foo;
dataService.getData = _getData;
return dataService;
}
I believe this facilitates public/private methods/vars.
For reference, this is the full code accessing my service:
app.js:
var gridApp = angular.module('gridApp', []);
// create the controller and inject Angular's $scope
gridApp.controller('mainController', ['$scope', 'dataService', function($scope, dataService) {
// create a message to display in our view
$scope.message = 'Angular is working';
var init = function(){
getPackageData();
};
var getPackageData = function (){
return dataService.getData().then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
}
);
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = ['$http'];
function dataService($http) {
var dataService = {};
var _getData = function () {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
dataService.getData = _getData;
return dataService;
}
})();

How can I passing Parameter angularjs factory $http and $stateParameters

App.factory('menuService', function ($http) {
var urlBase = 'Services/MenuService.asmx/GetAllMenu';
var factory = {};
factory.getAllMenus= function () {
return $http.get(urlBase);
};
return factory;
});
Controller:
App.controller("sampleController", function ($scope, menuService) {
$scope.List = [];
var menuData=function(data, status){
$scope.List = data;
console.log($scope.List);
}
menuService.getAllMenus().success(menuData);
});
/// Working perfect...
How can i use same service by other controller?
I've tried this one but wrong...
App.controller("viewDetailMenu", function ($scope, menuService, $stateParams) {
$scope.menu = menuService.getMenu($stateParams.id);
});
Here I share image how it look..
Please help me!...
You need to have all functions/methods defined if you want to use them. You getMenu function/method is not defined so it will generate an error. Please look at below code. You can add number of functions. You factory is share by all controllers so you can use it in any controller.
App.factory('menuService', function ($http) {
var urlBase = 'Services/MenuService.asmx/GetAllMenu';
var factory = {};
factory.getAllMenus= function () {
return $http.get(urlBase);
},
factory.getMenu=function(id){
return $http.get(urlBase +"/ID="+ id) // write it according to your API.
}
return factory;
});
And then,
App.controller("viewDetailMenu", function ($scope, menuService, $stateParams) {
$scope.menu = menuService.getMenu($stateParams.id).success(function(data,status){
}).error(function(data,status){
});
});

Angular can not find my factory

So I created with angular a small factory to get my local json file now I wanna pass that data to my controller but it can't find the factory name and says 'unresolved variable'.
Here is the snippet of my code what I guess is relevant for now.
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
});
})();
My goal is just to console log the $scope.teams, than I can do more with the data.
you should include "dataFactory" inside your controller
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
}); })();
I believe you need to pass your factory into the controller:
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});

AngularJS passing variable to service

I start with angularJS and I don't understant how you can push a variable from the controller to a service.
I try with $rootScope but the value of the variable was undefined
here is my service :
technoServices.factory('Config',['$rootScope','$resource',
function($rootScope,$resource,token){
return $resource('../../rest/config',null,{
get: {
method:'GET',
headers:{'X-Token':""+$rootScope.headers},
isArray:false}
});
}]);
and here is my controller :
var technoControllers = angular.module('technoControllers', []);
technoControllers.controller('loginCtrl', ['$scope','$rootScope', 'Techno',function($scope,$rootScope, Techno) {
$scope.getXtoken = function (user,psw){
$scope.config = Techno.post({username:user,password:psw},function(response,headers){
$scope.status= response.status;
$rootScope.headers = headers('X-Token');
if($rootScope.headers != null){
$scope.log = true;
}else{
$scope.log = false;
}
})};
}
]);
technoControllers.controller('configCtrl', ['$scope', 'Config', function($scope, Config) {
$scope.getConfig = function (){
$scope.maConfig = Config.get();
}
So as you can see , I need the variable from the response header of my first service in the header request of my seconde service. How can I do it ?
You can just use another service as shared service which will have the value and inject in both the controller and service.
Code snippet would be like this.
technoServices.factory('Shared',
function(){
var Shared={};
Shared.setValue=function(header){
Shared.header = header;
}
Shared.getValue=function(){
return Shared.header;
}
return Shared;
});
And in controller you can use as
technoControllers.controller('loginCtrl', ['$scope','$rootScope', 'Techno',function($scope,$rootScope, Techno, Shared) {
$scope.getXtoken = function (user,psw){
$scope.config = Techno.post({username:user,password:psw},function(response,headers){
$scope.status= response.status;
Shared.setValue(headers('X-Token'));
//$rootScope.headers = headers('X-Token');
if($rootScope.headers != null){
$scope.log = true;
}else{
$scope.log = false;
}
})};
}
]);
You can inject Shared service in Config to get data
technoServices.factory('Config',['$rootScope','$resource','Shared'
function($rootScope,$resource,token,Shared){
return $resource('../../rest/config',null,{
get: {
method:'GET',
//headers:{'X-Token':""+$rootScope.headers},
headers:{'X-Token':""+Shared.getValue()},
isArray:false}
});
}]);

Resources