how to set data in service in Angularjs - angularjs

In a table I am adding items such as product and price. I need to set the added data in service . can you please tell how to set the added data in service
routerApp.controller('products', function ($scope,myservice) {
$scope.items = [];
$scope.addRow = function(){
$scope.items.push({'Products':$scope.Products,'Price':$scope.Price});
}
});
service.js
routerApp.factory('myservice',function() {
var products =[]
var price=[]
var quantity=[]
var addProduct = function(data) {
products.push(data);
}
var addPrice = function(data) {
price.push(data);
}
var addQuantity = function(data) {
quantity.push(data);
}

you use getter and setters in your services.
Set data using setters and get it using getters simple.
Something like this...
var mod = angular.module('service', []);
mod.factory('sservice', ['$http',
function($http){
var anyName;
var setData = function(data) {
anyName=data;
}
}
]);

Related

Can't get data out of service in angularjs

I'm using a service in order to pass data between different instances of an AngularJS controller. I know that this is not the best way to do it but it's the way that fits my case. The problem is that I cannot get data out of that Service.
var app = angular.module('MovieApp', ['ngResource']);
app.factory('factMovies', function($resource) { //this returns some movies from MongoDB
return $resource('/movies');
});
app.service('SnapshotService', function(factMovies) {
//this is used to pass data to different instances of the same controller
//omitted getters/setters
this.snapshots = [];
this.init = function() {
var ctrl = this;
var resp = factMovies.query({}, function() {
if (resp.error) {
console.log(resp.error)
} else {
tempDataset = []
//do stuff and put the results in tempDataset
ctrl.snapshots.push(tempDataset);
console.log(tempDataset); //prints fine
return tempDataset;
}
});
};
});
app.controller('TileController', function(SnapshotService) {
this.dataset = [];
this.filters = [];
this.init = function() {
var ctrl = this;
var data = SnapshotService.init(function() {
console.log(ctrl.data); //doesn't even get to the callback function
});
};
});
I really can't figure out what I'm doing wrong..
SnapshotService.init() doesn't take any parameters - meaning the anonymous function you pass in with the SnapshotService.init() call in TileController does nothing.
What you need to do is add the parameter to the init function definition and then call it in the code:
app.service('SnapshotService', function(factMovies) {
//this is used to pass data to different instances of the same controller
//omitted getters/setters
this.snapshots = [];
this.init = function(cb) {
var ctrl = this;
var resp = factMovies.query({}, function() {
if (resp.error) {
console.log(resp.error)
} else {
tempDataset = []
//do stuff and put the results in tempDataset
ctrl.snapshots.push(tempDataset);
console.log(tempDataset); //prints fine
cb(ctrl.snapshots);
}
});
};
});

Reading model from model view returned from controller in angular

I have a action method like this
public async Task<ActionResult> Pc()
{
var v = await context.pcs.Select(w => new Code.pcs
{
id = w.id,
name = w.name,
province = w.province
}).ToListAsync();
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(v);
return View(v);
}
And I am calling this through angular http like this
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$http.get("Pc")
.then(function (response) {
$scope.myWelcome = response.data;
});
});
My question is how can I read model that returned by controller in angular?response.data is dumping whole view's html.
Change your controller's return type to string or JsonResult
public async string Pc()
{
var v = await context.pcs.Select(w => new Code.pcs
{
id = w.id,
name = w.name,
province = w.province
}).ToListAsync();
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(v);
return json;
}
and in your angular code make a modification to read json and then bind this data to DOM as per your requirement
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$http.get("Pc")
.then(function (response) {
$scope.myWelcome = response.data;
});
});

Angular services

I am trying to share an id between controllers in angular
I have created a service as follows:
app.factory("idService", function() {
var id;
addId = function(id) {
id = id;
};
getId = function() {
return id;
};
});
In my controller I am trying to use this service as follows:
app.controller('photoFormController', ['$scope', '$http', 'idService' , function($scope, $http, idService) {
$scope.id = idService.getId();
}]);
I am getting an error of can't call method of undefined, obviously I am injecting the service incorrectly. Can someone help ?
EDIT:
Based on the solution below, the service no longer generates errors, however I am unable to get the id varaible back, I can see that it gets set from one controller, however it remains undefined in when retrieving :
app.factory("idService", function() {
var id;
addId = function(id) {
id = id;
console.log("added id of: " + id);
};
getId = function() {
console.log("trying to return : " + id);
return id;
};
return {
addId: addId,
getId: getId
};
});
You need to return an object inside factory. This returned object is your service instance:
app.factory("idService", function() {
var _id; //use _id instead to avoid shadowing your variable with the same name id
var addId = function(id) { //use var to avoid creating a property on the global object
_id = id;
};
var getId = function() { //use var to avoid creating a property on the global object
return _id;
};
return {
addId : addId ,
getId : getId
};
});
This is because you need to place the id within an object.
fiddle
This idea is as follows:
myApp.controller('ctrl1', function($scope, myservice) {
$scope.updateId = function() {
myservice.setId($scope.input)
};
});
myApp.controller('ctrl2', function($scope, myservice) {
$scope.data = myservice.getData();
});
myApp.service('myservice', function() {
var myservice = this;
var data = {};
myservice.setId = function(newValue) {
data.id = newValue;
};
myservice.getData = function() {
return data;
}
});
This way the data object that you get from your service sort of static, and the mutable member that you are outputting is contained within it.
You don't need to create a service in order to share some variable, just use value():
JavaScript
angular.module('app',[]).
value('share', {id: 123}).
run(['share', function(share) {
console.log(share.id); // <= 123
share.id = 345;
}]).
controller('appController', ['$scope', 'share', function($scope, share) {
$scope.id = share.id; // <= 345
}]);
Plunker: http://plnkr.co/edit/m55hmFgBvi1rwVsYMeKU?p=preview
Example of service which store data between controllers:
'use strict';
angular
.module('app')
.factory('youService', youService);
youService.$inject = ['$rootScope'];
function youService($rootScope) {
var service = {};
var questions = [];
// Data
function getData() {
return questions;
};
function setData(newQuestion) {
questions.push(newQuestion);
};
function resetData() {
questions = {};
};
// Services
service.getData = getData;
service.setData = setData;
service.resetData = resetData;
return service;
};
In controller:
angular.module('app')
.controller('yourController', yourController);
stepFourController.$inject = ['$scope', 'youService'];
function yourController($scope, youService){
// Get saved data from service
$scope.model = youService.getData();
// Set data to service
youService.setData($scope.model);
// Reset data in service
youService.resetData();
};
Best way to share data between controller is through services or factories
The service can be written as:
var myApp = angular.module('myApp', []);
myApp.service('shareId', [function () {
var shareIdService = this;
shareIdService.id = '';
shareIdService.setId = function (id) {
shareIdService.id = id;
}
shareIdService.getId = function () {
return shareIdService.id;
}
}]);
or factory may be written like as
myApp.factory('shareId', [function () {
var id = '';
return {
setId:function (id){
id=id;
},
getId:function (){
return id;
}
}
}])

Angular Factory Async Calls- Updating Controller?

I have a Controller and Factory to handle lists. The controller needs to get the lists loaded by the factory and display it in the view. I can't have a getLists() method in the factory because this needs to load asynchronously from FireBase. Here is my controller code-
angular.module('myApp.controllers', []).
controller('ListCtrl', ["$scope","listFactory", function($scope, ListFactory) {
$scope.lists = [];
$scope.$on("list_update", function(snapshot)
{
console.log(snapshot);
});
}]).
controller("EditListCtrl", ["$scope","listFactory", function($scope, ListFactory)
{
$scope.name = "";
$scope.items = [];
$scope.itemCount = 10;
$scope.save = function()
{
var List = {"items":[]};
for(var i = 0; i < $scope.itemCount; i++)
{
var item = $scope.items[i];
if(item != null)
{
List.items.push(item);
}
else
{
alert("Please fill all items of the list.");
return false;
}
ListFactory.putList(List);
$scope.items = [];
$scope.name = "";
}
}
}]);
The listFactory looks like this-
angular.module("myApp.factories", [])
.factory("listFactory", [function()
{
var lists = [{"name":"test"}];
var ListRef = new Firebase("https://listapp.firebaseio.com/");
var factory = {};
factory.getLists = function()
{
// this won't work
}
factory.putList = function(List)
{
ListRef.child("lists").push(List);
}
ListRef.on("child_added", function(snapshot)
{
// How do I get this back to the controller???
});
return factory;
}]);
The ListRef will dispatch a "child_added" event where the snapshot argument is has the list data. I need to get this back to the controller somehow. I'd like to do this with events but I'm not sure how to do that between the factory and the controller. I don't want to use the root scope because I think that's bad practice.
I'm new to this- any help would be appreciated!
Firstly update your list variable to have a container object:
var lists = { items: [{ name: 'test' }] };
Then expose access to the list through the factory, eg:
factory.getLists = function() {
return lists;
}
Then set a scope var in your controller:
$scope.lists = ListFactory.getLists();
Then whenever the child_added event is triggered, update the lists.items, and the $scope from the controller should reflect the changes.

Sharing ajax data between multiple controllers in angular using service

Hi I have two controllers
pqsAppModule.controller('NotificationBoxController',function($scope,items) {
$scope.list = items.list();
})
and
pqsAppModule.controller('NotificationController',function($scope,items) {
$scope.list = items.list();
})
I need to create an "items" service that would do an ajax request and return data for any controller which would have it injected. And I want, that the query will be done only once, and items will be shared between all controllers.
pqsAppModule.factory('items', function($http) {
var items = [];
var itemsService = {};
$http.get('api/notification').then(function(response){
items = response.data;
});
itemsService.list = function() {
return items;
};
return itemsService;
});
But I don't understand why angular makes the request, and receives data, but all items in controllers are empty.
It happens because the factory should be defined by different way.
(I took dummy URL only to load data by async way)
HTML
<div ng-controller="NotificationBoxController">
<button ng-click="showMe();">press me</button>
<pre>NotificationBoxController: {{items.getList()|json}}</pre>
</div>
<div ng-controller="NotificationController">
<pre>NotificationController: {{items.getList()|json}}</pre>
</div>
JS
var pqsAppModule = angular.module('myApp', []);
pqsAppModule.controller('NotificationBoxController',function($scope,items) {
$scope.items = items;
$scope.showMe= function(){
items.query();
}
});
pqsAppModule.controller('NotificationController',function($scope,items) {
$scope.items = items;
});
pqsAppModule.factory('items', function ($http) {
var current = {};
var address = 'Singapore, SG, Singapore, 153 Bukit Batok Street 1';
var URL = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=true';
var factory = {
query: function () {
var data = $http({method: 'GET', url:URL}).then(function (result) {
current = result.data.results[0];
}, function (result) {
alert("Error: No data returned");
});
},
getList: function () {
return current;
}
}
return factory;
});
Demo Fiddle
From this example we call items.getList() from HTML for both controllers. But if we want to update the model through the controller, we need a listener like $watch
Try this
$http.get('api/notification').then(function(response){
angular.foreach(response.data,function(item) {
items.push(item);
});
});
Basically do not create a new array but fill the existing one.

Resources