AngularJs send value of a controller to a service - angularjs

Question is simple, i have value in a controller, and i want to send this value to another controller.
I have this code :
var app = angular.module("MyApp", []);
app.factory("UserService", function() {
var users = //how to get the value user of MyCtrl ?
return {
all: function() {
return users;
},
first: function() {
return users[0];
}
};
});
app.controller("MyCtrl", function($scope, UserService) {
var users = ["Peter", "Daniel", "Nina"];
$scope.users = UserService.all();
});
app.controller("AnotherCtrl", function($scope, UserService) {
$scope.firstUser = UserService.first();
});
I didn't know how to get value of var users = ["Peter", "Daniel", "Nina"]; from the controller MyCtrl in UserService ?
live exemple :http://jsbin.com/vacutodo/1/edit?html,js,output

You can inject it into your function:
app.factory('UserService', ['MyCtrl', function(MyCtrl) {
var users = MyCtrl.users;
...
};
app.controller("MyCtrl", function($scope, UserService) {
var users = ["Peter", "Daniel", "Nina"];
$scope.users = UserService.all();
return {
users: users
};
});

Related

I want to share data stored in variable from one controller to another

I have data in one controller and now I want to share it with another but both controller has different modules. I have used $rootscope but it didn't work. I have used service it also didn't work. link here Service
Is there any other way to do. I have spent one week for this please help me.
toolbar.controler
(function ()
{
'use strict';
angular
.module('app.toolbar')
.controller('ToolbarController', ToolbarController);
function ToolbarController($rootScope, $mdSidenav, msNavFoldService, $translate, $mdToast, $location, $localStorage, $http, $scope)
{
var vm = this;
vm.name = $localStorage.name;
vm.userId = $localStorage._id;
vm.readNotifications = function(notifId){
$http({
url: 'http://192.168.2.8:7200/api/readNotification',
method: 'POST',
data: {notificationId: notifId, userId: vm.userId}
}).then(function(res){
vm.rslt = res.data.result1;
console.log(vm.rslt);
vm.refresh();
$location.path('/sharedwishlistdetails');
}, function(error){
alert(error.data);
})
}
}
})();
The data stored here in vm.reslt.
toolbar.module.js
(function ()
{
'use strict';
angular
.module('app.toolbar', [])
.config(config);
/** #ngInject */
function config($stateProvider, $translatePartialLoaderProvider)
{
$translatePartialLoaderProvider.addPart('app/toolbar');
}
})();
Now I want that result for this controller.
sharedwishlistdetails.controller.js
(function ()
{
'use strict';
angular
.module('app.sharedwishlistdetails')
.controller('SharedWishlistDetailsController', SharedWishlistDetailsController);
/** #ngInject */
//NotificationsController.$inject = ['$http', '$location'];
function SharedWishlistDetailsController($http, $location, $localStorage, $rootScope, $scope)
{
var vm = this;
vm.uid = $localStorage._id;
}
})();
shareddata.service.js
(function ()
{
'use strict';
angular
.module('app.core')
.factory('shareData', shareDataService);
/** #ngInject */
function shareDataService($resource,$http) {
var shareData = {};
return shareData;
}
})();
write a service in 'app.toolbar' module
angular.module('app.toolbar').service('ServiceA', function() {
this.getValue = function() {
return this.myValue;
};
this.setValue = function(newValue) {
this.myValue = newValue;
}
});
In your toolbarController , inject ServiceA and set data -
vm.readNotifications = function(notifId){
$http({
url: 'http://192.168.2.8:7200/api/readNotification',
method: 'POST',
data: {notificationId: notifId, userId: vm.userId}
}).then(function(res){
vm.rslt = res.data.result1;
ServiceA.setValue(vm.rslt);
console.log(vm.rslt);
vm.refresh();
$location.path('/sharedwishlistdetails');
}, function(error){
alert(error.data);
})
}
Now write another service for 'app.sharedwishlistdetails' module -
angular.module('app.sharedwishlistdetails',['app.toolbar']).service('ServiceB', function(ServiceA) {
this.getValue = function() {
return ServiceA.getValue();
};
this.setValue = function() {
ServiceA.setValue('New value');
}
});
Now inject ServiceB in your SharedWishlistDetailsController controller and access data -
var sharedData = ServiceB.getValue();
How could $rootScope failed in your code it would be appreciated if you paste your code: never mind here is an example that will help you out:
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.
The rootScope is available in the entire application.If a variable has the same name in both the current scope and in the rootScope, the application use the one in the current scope.
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});

How to use a service defined in another module than the controller calling it?

I have a module with a service defined:
var ngError = angular.module('ngError', []);
ngError.service('ErrorService', ['$scope', function($scope) {
$scope.displayErrors = function(errors) {
alert(errors);
}
}]);
Then I have another module:
var ngLogin = angular.module('ngLogin', ['ngError']);
Which has a controller that attempts to use the first service defined on ngError:
ngLogin.controller('LoginCtrl', ['$scope', 'LoginService', 'ErrorService', function($scope, LoginService, ErrorService) {
$scope.user = {};
$scope.user.id = 0;
$scope.user.token = '';
$scope.login = function(callback) {
LoginService.login($scope.user.username, $scope.user.password, function(token) {
$scope.setToken(token);
$scope.$apply();
if (typeof callback === 'function') {
callback(callback);
}
}, function(errors) {
ErrorService.displayErrors(errors);
});
};
}]);
But some reason this is throwing the following error:
Unknown provider: $scopeProvider <- $scope <- ErrorService
You cannot use $scope within a service. Change the service as follows and it will work:
var ngError = angular.module('ngError', []);
ngError.service('ErrorService', [function() {
this.displayErrors = function(errors) {
alert(errors);
}
}]);
Try like this , working best for me
var app = angular.module('MyApp', []);
app.service('MyService', function () {
var property = 'First';
this.myFunc = function (x) {
return x*5;
}
});
//
controller 2 under second app module
var app = angular.module('AnotherApp',[]);
app.controller("AnotherAppCtrl", function($scope,MyService) {
$scope.value = MyService.myFunc(4);
});

controller pass $scope value to another controller

I'm very new to AngularJS, how can I pass input scope from first controller to the second controller for the data $scope.requestURL
I've search about the service method but I have no idea how to apply it.
.controller('ZipController', ['$scope', function($scope) {
$scope.zipCode = '10028';
$scope.setURL = function() {
$scope.requestURL = 'http://congress.api.sunlightfoundation.com/legislators/locate?zip=' + $scope.zipCode + '&apikey=xxxxx';
};
}])
.controller('ListController', ['$scope', '$http',
function($scope, $http) {
$http.get($scope.requestURL).success(function(data) {
console.log(data.results);
$scope.congress = data.results;
});
}]);
Here is a quick solution: ..you don't have to use the $http core service for your case:
You can also read more about angular's constant service..
(function(angular) {
var app = angular.module('myServiceModule', []);
app.controller('ZipController', function($scope, myService) {
$scope.zipCode = '10028';
myService.setFunc($scope.zipCode);
myService.zipCode = $scope.zipCode;
});
app.controller('ListController', function($scope, myService) {
$scope.requestURL = myService.getFunc();
});
app.factory('myService', function() {
var zipCode;
var setFunc = function(zip) {
zipCode = zip;
};
var getFunc = function() {
return 'http://congress.api.sunlightfoundation.com/legislators/locate?zip=' + zipCode + '&apikey=xxxxx'
};
return {
zipCode: zipCode,
setFunc: setFunc,
getFunc: getFunc
};
});
})(window.angular);
Try setting it to $rootScope.requestURL and access it from the second controller.

can controllers create arbitrary properties in the $rootScope in Angular

Is it legal for a controller to do something like this in Angular?
$rootScope.someArbitaryObject = ["fee", "fie", "fo", "fum];
or
$rootScope.foo = {name: "Jane Q. Public", favoriteColor: "green"}
Yes, it is legal but only if you want ALL controllers to have access to that model.
A better practice is to use services that you can then inject to one or more controllers:
var myApp = angular.module('myApp', []);
myApp.factory('MyService', function () {
return { message: "I'm data from a service" };
});
myApp.controller('FirstCtrl', function($scope, MyService) {
$scope.data = MyService;
});
myApp.controller('SecondCtrl', function($scope, MyService) {
$scope.data = MyService;
});
Any change you make to MyService properties in one controller will affect all the other controllers that use MyService.
regarding the question in your comments, a good way to share date is through localstorage (or sessionStorage). I wrote a storageService which allows you to save, load and delete.
angular.module(yourApplication).service('storageService', [
function() {
// implementation using localStorage. Future possibility to user $cookie service here, or sessionStorage, depends on what you want
return {
save: function(key, jsonData, expirationMin){ // default is 30 minute expiration
if(!expirationMin)
expirationMin = 30;
var expirationMS = expirationMin * 60 * 1000;
var record = {
value: JSON.stringify(jsonData),
timestamp: new Date().getTime() + expirationMS
};
localStorage.setItem(key, JSON.stringify(record));
return jsonData;
},
load: function(key){
var record = JSON.parse(localStorage.getItem(key));
if (!record){
return false;
}
return (new Date().getTime() < record.timestamp && JSON.parse(record.value));
},
remove: function(key){
localStorage.removeItem(key);
}
};
}
]);
Another way using services (Modified Yoni's code a little):
var myApp = angular.module('myApp', []);
myApp.service('MyService', function () {
var someData = 'test';
return {
getData: function(){ return someData},
setData: function(input){ someData = input;}
};
});
myApp.controller('FirstCtrl', function($scope, MyService) {
$scope.data = MyService.getData();
});
myApp.controller('SecondCtrl', function($scope, MyService) {
$scope.data = MyService.getData;
});

Factory not keeping data when used in controller

I have a factory House
'use strict';
myApp
.factory('House', [ '$http', '$location', '$rootScope', function($http, $location, $rootScope){
var numberOfDoors;
return {
loadHouse: function(){
numberOfDoors = 1;
},
numberOfDoors: numberOfDoors
};
}]);
And I have a controller Owner
myApp
.controller('OwnerCtrl', ['$rootScope', '$scope', '$location', 'House', function($rootScope, $scope, $location, House) {
$scope.buildMe = function() {
//use value from house
var sayHelloToDoors = House.numberOfDoors;
};
}]);
If I run a function House.loadHouse() in some other controller in order to set the variable numberOfDoors - I do set it, but when I switch to a page to reuse that number, I get a undefined message in Owner controller.
Why the value is cleared? It seems like another instance of House is transfered.
Could anybody help?
This is because you're assigning the value of private numberOfDoors to the field numberOfDoors in the factory.
// This following snippet ...
myApp.factory('house', function() {
var numberOfDoors;
return {
numberOfDoors: numberOfDoors
};
});
// ... will actually become
myApp.factory('house', function() {
var numberOfDoors; // === undefined
return {
numberOfDoors: undefined
};
});
Even if you would assign the private numberOfDoors an initial value, it would not behave the way you want it to.
myApp.factory('house', function() {
var numberOfDoors = 123;
return {
loadHouse: function() {
numberOfDoors = 1; // will change the private variable
// not the exposed object variable
},
numberOfDoors: numberOfDoors // will always be 123
};
});
Easiest way to make this work is doing something like this:
myApp.factory('house', function() {
return {
reset: function() {
this.numberOfDoors = 0;
},
numberOfDoors: 0
};
});
You can play with in action at this plunker.
Edit:
To encapsulate the number of doors you could do something like this:
myApp.factory('house', function() {
var _numberOfDoors = 0;
return {
reset: function() {
_numberOfDoors = 0;
},
numberOfDoors: function(value) {
if(value!==undefined) {
_numberOfDoors = value;
}
return _numberOfDoors;
}
};
});
Now from your controller you can:
var count = house.numberOfDoors(); // Get the numberOfDoors
house.numberOfDoors(++count); // Set the numberOfDoors
You'll have to change "numberOfDoors: numberOfDoors" to "numberOfDoors: function(){return numberOfDoors;}"
Please see this simple: (available in plnkr)
var service = (function(){
var privateVar = 0;
return{
updateVar: function(val){
privateVar = val;
},
getVar2: privateVar,
getVar: function(){
return privateVar;
}
}
})();
var instanceA = (function(){
service.updateVar(1);
alert(service.getVar());
})();
var instanceB = (function(){
alert(service.getVar());
alert(service.getVar2);
})();

Resources