getting varriable from service to the controllers - javascript

im trying to get a varriable from this service but i can't manage to do this. i've looked online and got nothing.service:
.factory('localStorageService', function($rootScope){
$rootScope.go = function(task) {
var dataReceiver = localStorage.getItem('taskData');
var array = [];
var newArray = array.push({"title" : task});
if(dataReceiver === null) {
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
console.log(dataReceiver);
}
else {
array = JSON.parse(dataReceiver);
var newArray2 = array.push({"title" : task});
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
for(var i = 0; i < newArray2; i++) {
console.log(dataReceiver[i].title);
}
}
return dataReceiver;
}
})
controller:
.controller('PlaylistsCtrl', function($scope, PlaylistService, localStorageService) {
console.log(localStorageService.go());
})
it says it cannot read property go of undefined

You need to declare with module the factory belongs to, that's why localStorageService is undefined in your controller. And yes, you also shouldn't be appending go to rootScope. Your factory should look like this:
angular.module('myApp', []).factory('localStorageService', function($rootScope){
this.go = function(task) {
var dataReceiver = localStorage.getItem('taskData');
var array = [];
var newArray = array.push({"title" : task});
if(dataReceiver === null) {
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
console.log(dataReceiver);
}
else {
array = JSON.parse(dataReceiver);
var newArray2 = array.push({"title" : task});
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
for(var i = 0; i < newArray2; i++) {
console.log(dataReceiver[i].title);
}
}
return dataReceiver;
};
return this;
});
By returning the factory object it and all of it's methods are then available when injected into your controller.

Your problem is that you put the method 'go' on the rootscope and not on the factory.
Your factory is returning the object dataReceiver which does not have a method 'go'.
Put the 'go' method on the object that is being returned from the factory and you will be able to get it.
Here is a basic plunkr: http://plnkr.co/edit/wbCedJx8BJ4nOvuNWQc7
JavaScript:
var app = angular.module('app', []);
app.controller('appCtrl', function ($scope, myFactory) {
$scope.greetings = myFactory.go();
});
app.factory('myFactory', function () {
this.go = function () {
return 'hello from factory';
};
return this;
});
Markup:
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="appCtrl">
<h1>Greetings: {{ greetings }}</h1>
</body>
</html>
Hope this helps.

Service
app.factory('localStorageService', ['$rootScope', function($rootScope) {
return {
go: function() {
//do your stuff here
var dataReceiver = localStorage.getItem('taskData');
var array = [];
var newArray = array.push({"title" : task});
if(dataReceiver === null) {
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
console.log(dataReceiver);
}
else {
array = JSON.parse(dataReceiver);
var newArray2 = array.push({"title" : task});
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
for(var i = 0; i < newArray2; i++) {
console.log(dataReceiver[i].title);
}
}
return dataReceiver;
}
}
}]);
controller
app.controller('PlaylistsCtrl',
function PlaylistsCtrl($scope, PlaylistService, localStorageService) {
console.log(localStorageService.go())
}
)

Related

$watch function is not getting triggered

I have a service which returns reponse. In response I have count of Users. I have a var userCount and I have a watch() on this userCount var.
var userCount=null;
var eventPromise = userSer.load(query, deviceType,$scope.duration);
eventPromise.then(function(response) {
console.log(response)
var dataLength = response.users.length;
$scope.numberOfRecords = dataLength;
if(dataLength > 0){
userCount = response.beaconCount;
setUserCount(userCount);
}
var setUserCount=function(data){
userCount=data;
};
var getUserCount=function(){
return userCount;
}
// This $watch function is not getting trigger as we are changing value of userCount from null to response.userCount.
$scope.$watch(userCount, function(newVal){
alert("M in watch func");
$scope.gridOptions.columnDefs[0].displayName = 'Beacon(' + getUserCount() + ')';
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
})
You have messed up the usage of $scope.$watch, the correct usage of $scope.$watch is as below, refer docs here:
Usage1: watching changes of variable belongs to $scope.
$scope.userCount = null;
$scope.$watch("userCount", function() { ... });
Usage2: watching changes of variable not belongs to $scope.
var userCount = null;
$scope.$watch(function() { return userCount; }, function() { ... });
refer the below example.
angular.module("app", [])
.controller("myCtrl", function($scope, $timeout) {
$scope.data = null;
var data2 = null;
$scope.$watch("data", function() {
console.log("data change detected.");
});
$scope.$watch(function() { return data2; }, function() {
console.log("data2 change detected.");
});
$timeout(function() {
$scope.data = {id: 1};
data2 = {id: 2};
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
</div>
You cannot $watch any variable like this. Assign the userCount variable to $scope and it will work.
$scope.userCount = null;
userSer.load(query, deviceType, $scope.duration).then(function (response) {
console.log(response);
var dataLength = response.users.length;
$scope.numberOfRecords = dataLength;
if (dataLength > 0) {
$scope.userCount = response.beaconCount;
}
});

share objects between controllers using services [duplicate]

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 5 years ago.
I have to controllers the first controller is "cockpitController"and the other one "idCardSupplierWarnController" .In the first controller i set my objects and i checked if the set work and it work i can see all my objects but when i want to get my objects in the other controller then all my objects are null .
PS: I checked this solution it's working for the case that the controller is in the same Window of the navigator but in my case it's in new window using $window.open(url).
Le service idCardSupplierWarnService :
var app = angular.module('idCardSupplierWarn');
app.service('idCardSupplierWarnService', function () {
this.idRefNum = "";
this.idSupNum = "";
this.codeSuppNum = "";
this.setParam = function (paramSet) {
console.log(paramSet);
this.idRefNum = paramSet.designRefPart;
this.idSupNum = paramSet.idSuppNumber;
this.codeSuppNum = paramSet.codeSupp;
};
this.getParamSupNum = function () {
return this.idSupNum;
};
this.getParamCodeSupNum = function () {
return this.codeSuppNum;
};
this.getParamIdRefNum = function () {
return this.idRefNum;
};
});
Le controller cockpitController :
(function () {
angular
.module("cockpit", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
.controller('cockpitController', ['$scope', '$translate', 'serviceCockpit','idCardSupplierWarnService', '$window', function ($scope, $translate, serviceCockpit,idCardSupplierWarnService,$window) {
var urlSuppliersWarning = 'rest/suppliers/warnings';
var urlSuppliersWarningByRefForDetails = 'rest/suppliers/warnings/supplier/ref/search';
var self = this;
serviceCockpit.loadData([urlSuppliersWarning]).then(function (results) {
self.suppliersWarning = results[0].data;
});
this.change = function () {
if (this.openWindow) {
this.openWindow = false;
}
else {
this.openWindow = true;
}
};
$scope.openNewWindowRef = function (url, params) {
console.log(params);
idCardSupplierWarnService.setParam(params);
console.log(idCardSupplierWarnService.getParams());
$window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
};
$scope.openNewWindowSupp = function (url, params) {
idCardSupplierWarnService.setParam(params);
console.log(idCardSupplierWarnService);
$window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
};
this.process = function (items) {
if (items.origin == 'reference' || items.origin == 'suppliers' || items.origin == 'supplierAccounts' || items.origin == 'supplierAddressCodes' || items.origin == 'reset') {
serviceCockpit.loadData([urlSuppliersWarningByRefForDetails], items).then(function (results) {
self.suppliersWarningDetails = results[0].data;
});
}
serviceCockpit.loadData([urlSuppliersWarning], items).then(function (results) {
self.suppliersWarning = results[0].data;
});
}
}]);
})();
Le controller **idCardSupplierWarnController :**
(function () {
angular
.module("idCardSupplierWarn", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
.controller('idCardSupplierWarnController', ['$translate', '$scope', 'serviceCockpit','idCardSupplierWarnService', function ($translate, $scope, serviceCockpit,idCardSupplierWarnService) {
var urlSupplierWarningByRefDetail = 'rest/suppliers/warnings/supplier/details';
var self = this;
var params = {} ;
params.idRefNum = idCardSupplierWarnService.getParamIdRefNum();
params.idSupNum = idCardSupplierWarnService.getParamSupNum();
params.codeSuppNum = idCardSupplierWarnService.getParamCodeSupNum();
console.log(params.codeSuppNum);
serviceCockpit.loadData([urlSupplierWarningByRefDetail], params).then(function (results) {
self.suppliersWarningsList = results[0].data;
});
}]);
})();
"This" in the functions of your service refers to the individual functions in your service, not the service itself.
Modify your service to look like this:
app.service('idCardSupplierWarnService', function () {
var service = this
service.idRefNum = "";
service.idSupNum = "";
service.codeSuppNum = "";
service.setParam = function (paramSet) {
console.log(paramSet);
service.idRefNum = paramSet.designRefPart;
service.idSupNum = paramSet.idSuppNumber;
service.codeSuppNum = paramSet.codeSupp;
};
service.getParamSupNum = function () {
return service.idSupNum;
};
service.getParamCodeSupNum = function () {
return service.codeSuppNum;
};
service.getParamIdRefNum = function () {
service this.idRefNum;
};
return service
});
You need to inject idCardSupplierWarn module into cockpit module, to access the service.
angular.module("cockpit", ['mm.foundation', 'security', 'message', `isteven-multi-select`, `idCardSupplierWarn`])

Sharing object array between controllers while working with modal window in angularJS

I am trying to work with an object array which I am sharing among two controllers one of which is dealing with modal window.
Here is the js code.
angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ui.bootstrap'])
.service('Faq', function ($http) {
this.faqList = [];
this.faqList = $http.get('/Json/faq.json');
this.getFaqs = function ()
{
return this.faqList;
}
this.addfaq = function (obj) {
this.faqList.push(obj);
};
})
.controller('AppCtrl', function ($scope,$modal,Faq) {
$scope.faqData = [];
Faq.getFaqs().then(function (msg) {
$scope.faqData = msg.data;
});
}
$scope.show = function () {
$modal.open({
templateUrl: "faqAddUpdate.html",
controller: "faqctrl"
});
};
})
.controller('faqctrl', function ($scope, $modalInstance, Faq) {
$scope.question = '';
$scope.id = '';
$scope.answer = '';
$scope.editFaq = function (id) {
$scope.divFaq = true;
$scope.faqs = [];
Faq.getData().then(function (msg) {
$scope.faqs = msg.data;
var l = $scope.faqs.length;
for (var i = 0; i < l; i++) {
if ($scope.faqs[i].id == id) {
$scope.question = $scope.faqs[i].question;
$scope.id = $scope.faqs[i].id;
$scope.answer = $scope.faqs[i].answer;
}
}
});
};
$scope.AddUpdateFAQ = function () {
var faq = {
id: $scope.id,
question: $scope.question,
answer: $scope.answer
};
Faq.addfaq(faq);
console.log(faq);
$modalInstance.close();
};
$scope.Cancel = function () {
$modalInstance.dismiss();
};
});
but when I am submitting the data through the modal it says this.faqList.push is not a function.
It is because your faqList variable is not an array.
You overide the first definition:
this.faqList = [];
With this:
this.faqList = $http.get('/Json/faq.json');
But $http.get returns a promise (see doc), not an array.
You should do something like this:
this.faqList = [];
$http.get('/Json/faq.json').then(function(result) {
// process your results here
this.faqList = result.data;
});
Not tried, but this is within the function scope, so create a _this var first might help:
this.faqList = [];
this.faqList = $http.get('/Json/faq.json');
var _this = this;
this.getFaqs = function ()
{
return _this.faqList;
}
this.addfaq = function (obj) {
_this.faqList.push(obj);
};

service is returning undefined in the array in angularjs

I am facing trouble with my angularjs script.
Background: I am trying to determine the location of the user, I have written my business logic in my service from where I am returning the location of the user.
Problem : The result I am getting in my console is as below :
[undefined] landingPage.js:11 undefined landingPage.js:11 undefined
var app = angular.module("PublicEvents", ["geolocation"]);
app.controller("iterator", ["$scope", "$http", "locationService1", function($scope, $http, locationService1){
$scope.targetCity = [];
$scope.targetCity.push(locationService1.location());
console.log($scope.targetCity);
$scope.$watch(function () { return locationService1.cityNameArray; },
function (value) {
$scope.targetCity = value;
console.log($scope.targerCity);
}
);
}]);
app.service("locationService1",['$http','$window', function( $http, $window){
var access = this;
this.location = function(){
$window.navigator.geolocation.getCurrentPosition(function(position) {
access.lat = position.coords.latitude;
access.long = position.coords.longitude;
access.locationData = [];
access.cityNameArray = [];
/*var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=18.9750,72.8258&sensor=true";*/
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+access.lat+","+access.long+"&sensor=true";
//AJAX CALL TO GET THE LOCATION
$http.get(url).then(function(response) {
access.locationData = response.data;
if(access.locationData.status == "OK" || access.locationData.status==200 ) {
angular.forEach(access.locationData.results, function(value, key){
var len = value.address_components.length;
for(var i = 0; i< len; i++){
if(value.address_components[i].types[0] =="locality" || value.address_components[i].types[0] =="sublocality_level_1"){
access.cityNameArray.push(value.address_components[i].long_name);
}
}
});
};
});
return access.cityNameArray;
});
};
}]);
Seems like you need to return data from an async call and you are returning value from outside the function. I'd suggest you to use promise pattern in such situation.
this.location = function(){
$window.navigator.geolocation.getCurrentPosition(function(position) {
access.lat = position.coords.latitude;
access.long = position.coords.longitude;
access.locationData = [];
access.cityNameArray = [];
/*var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=18.9750,72.8258&sensor=true";*/
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+access.lat+","+access.long+"&sensor=true";
//return promise from here..
return $http.get(url).then(function(response) {
access.locationData = response.data;
if(access.locationData.status == "OK" || access.locationData.status==200 ) {
angular.forEach(access.locationData.results, function(value, key){
var len = value.address_components.length;
for(var i = 0; i< len; i++){
if(value.address_components[i].types[0] =="locality" || value.address_components[i].types[0] =="sublocality_level_1"){
access.cityNameArray.push(value.address_components[i].long_name);
}
}
});
};
return access.cityNameArray; //returned from success callback
});
});
};
Inside controller you need to use .then function to get data from the service loacation function. You were doing console.log when you are doing async call which doesn't return anything.
locationService1.location().then(function(data){ //success callback.
$scope.targetCity.push(data)
},function(error){ //error callback.
console.log(error)
});

AngularJS share function/common code in a controller

I have a subroutine I want to use in my controller. In the case or working with data, a new record blanks fields, as would a screen clear, and after some other processes, I would like to clear the editable fields on the view.
Controller:
angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
function ($scope, ServiceData) {
function ClearMemberStruture()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
$scope.Members = ServiceData.GetAllMembers();
$scope.member = {};
ClearMemberStruture();
$scope.DeleteMember = function(Member) {
ServiceData.DeleteMember(Member.Key);
$scopeEditMode = false;
};
$scope.EditMember = function(Member) {
var EditMember = ServiceData.GetOneMember(Member.Key);
EditMember.$bindTo($scope, "member").then(
function(unbind) {
$scope.MemberUnbind = unbind;
});
$scopeEditMode = true;
};
$scope.SaveMember = function(Member) {
if( ! $scopeEditMode )
{
$scope.member = ServiceData.AddMember(Member);
ClearMemberStructure();
}
};
$scope.ClearMember = function() {
$scope.member.unbind;
ClearMemberStructure();
$scope.MemberUnbind();
};
}
]);
ClearMemberStructure() is used to reset the common structure fields and the Edit flag which controls showing information on the screen. When I run this code, I always get a
ReferenceError: ClearMemberStructure is not defined
How can I share this common function in my controller in AngularJS?
If I add a Factory, I can achieve this using calls to the factory:
angular.module('MyApp').factory("MemberRecord", function() {
var Member = {
Key: "",
Name: "",
Points: ""
};
return {
Clear: function() {
Member.Key = "";
Member.Name = "";
Member.Points = "";
return Member;
}
};
}
);
And then in the controller:
$scope.member = MemberRecord.Clear();
Is there a way to do the simply function style code sharing, as I do want this to be handled as a private function, but cannot get it to recognize the function in the controller.
var ClearMemberStruture = function()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
is your solution to declare ClearMemberStruture without breaking your whole code.
I use a separate file with factories to share code between controllers.
App.factory('CommonServices', function ($http) {
return {
createComment: function($api_key, $post_id, $comment) {
var comment_data = {
content: $comment
};
return $http({
url: '/api/v1/posts/' + $post_id + '/comments',
method: "POST",
headers: { 'X-API-TOKEN': $api_key },
params: comment_data,
data: ''
})
}
});
Then in a controller you can access the common functions like:
$scope.saveComment = function($post_id) {
CommonServices.createComment($scope.api_key, $post_id, $scope.comment.text)
.then(function(_data) {
var index = $scope.feed_items.filter(function (post) { return post.id == $post_id });
index[0].comments.unshift(_data.data);
$scope.showComment = false;
});
}
I prefer to use factory for Member and encapsulate method there. But you can try the easier way:
angular.module('MyApp').controller('Ctrl', ["$scope", "ServiceData",
function ($scope, ServiceData) {
var that = this;
that.ClearMemberStruture = function()
{
$scope.member.Key = "";
$scope.member.Name = "";
$scope.member.Points = 0;
$scope.EditMode = false;
}
$scope.Members = ServiceData.GetAllMembers();
$scope.member = {};
that.ClearMemberStruture();
$scope.DeleteMember = function(Member) {
ServiceData.DeleteMember(Member.Key);
$scopeEditMode = false;
};
$scope.EditMember = function(Member) {
var EditMember = ServiceData.GetOneMember(Member.Key);
EditMember.$bindTo($scope, "member").then(
function(unbind) {
$scope.MemberUnbind = unbind;
});
$scopeEditMode = true;
};
$scope.SaveMember = function(Member) {
if( ! $scopeEditMode )
{
$scope.member = ServiceData.AddMember(Member);
ClearMemberStructure();
}
};
$scope.ClearMember = function() {
$scope.member.unbind;
ClearMemberStructure();
$scope.MemberUnbind();
};
}
]);

Categories

Resources