angularjs data in service can not be share between different controller - angularjs

I create service :
.factory('patientListBarService', function() {
var data = {
pages: 0,
total:0
};
return data;
})
my ctl 1:
.controller('patientCtl', ['$scope', '$http', 'patientListBarService', function($scope, $http, patientListBarService){
console.log(patientListBarService);
$scope.pages = patientListBarService.pages;
$scope.total = patientListBarService.total;
$scope.$watch('patientListBarService.pages', function(newVal, oldVal, scope) {
console.log('====pages:' + patientListBarService.pages);
$scope.pages = patientListBarService.pages;
});
$scope.$watch('patientListBarService.total', function(newVal, oldVal, scope) {
console.log('====total:' + patientListBarService.total);
$scope.total = patientListBarService.total;
});
}]);
my ctl 2:
controller('patientListCtl', ['$scope', 'patients', '$http', 'patientListBarService', function($scope, patients, $http, patientListBarService){
console.log("----patient list ctl----");
console.log(patients);
patientListBarService.pages = patients.config.pages;
patientListBarService.total = patients.config.total;
}]);
the ctl1 run before ctl2.
after ctl2 run, ctl1's
$scope.pages
$scope.total
display the right value on my view.
however, their display not change after I run ctl2 more times.
I am new to ng...
Anyone help me? thanks !!!

If you wrap your service data into an object, you don't need the watches and the values will be synced automatically
.controller("Test1", function($scope, Serv){
$scope.serv = Serv.data;
$scope.modify = function(){
$scope.serv.param1 = Math.random()*100;
$scope.serv.param2 = Math.random()*100;
}
})
.controller("Test2", function($scope, Serv){
$scope.serv = Serv.data;
})
.factory("Serv", function(){
var data = {
param1: '',
param2: ''
}
return {
data: data
}
});
jsbin

Related

Use data from factory in controller in angularjs

I am very new to AngularJS.
I want to pass an array data from my app factory to app controller.
Here is my app.factory code.
App.factory('buyFactory', ['$http', function($http) {
factory.Search = function(scope, d) {
var data = scope.search;
scope.CarsData = [];
all_cars = [];
scope.isLoading = true;
$http.post(ajaxurl + '?action=search_car', d)
.success(function(response) {
angular.forEach(response, function(c) {
c.price = parseFloat(c.price);
c.driven = parseFloat(c.driven);
c.year = parseFloat(c.year);
});
angular.forEach(response, function(value, key) {
all_cars.push(value);
scope.CarsData = all_cars;
scope.TotalItems = scope.CarsData.length;
scope.isLoading = false;
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
scope.isLoading = false;
});
}
return factory;
}]);
and this is app.controller as
App.controller('buyController', ['$scope', '$http', 'buyFactory', '$filter', function($scope, $http, buyFactory, $filter) {
$scope.CarsScroll = buyFactory.Search.CarsData();
$scope.loadMore = function() {
var last = $scope.CarsScroll[$scope.CarsScroll.length - 1];
for (var i = 1; i <= 3; i++) {
$scope.CarsScroll.push(last + i);
}
};
//scroll
}]);
I want to use output obtained from factory i.e. CarsData as a variable in my app controller. But I am not able to get it. I have tried using services also. Is there method to use array data in a simplest way.
Your syntax is completely broken, i would recommend following any course of AngularJS. As for how to correctly do what you are trying to would look something like this
app.factory('buyFactory', ['$http', '$q', function($http, $q) {
var factory = {
search: function(d) {
return $q(function(resolve, reject) {
$http.post(ajaxurl + '?action=search_car', d).then(function(response) {
angular.forEach(response, function(c) {
c.price = parseFloat(c.price);
c.driven = parseFloat(c.driven);
c.year = parseFloat(c.year);
});
var carsData = [];
angular.forEach(response, function(value, key) {
carsData.push(value);
})
var result = {
carsData: carsData,
total: carsData.length
}
resolve(result);
}, function(error) {
reject(error);
})
});
}
}
return factory;
}]);
app.controller('buyController', ['$scope', '$http', 'buyFactory', '$filter', function($scope, $http, buyFactory, $filter) {
buyFactory.search().then(function(result) {
var cars = result.carsData;
var total = result.total;
})
}]);
Note: i do not know what the d parameter is for neither why the angular.forEach statements so it might not be fully functional. But this is more as guideline for how your factory should look and be used.

retrieving one record form firebase database. Ionic App

Hi I'm doing an application in Ionic Creator and I would like to retrieve one record from database that has given email address (userId) .
this is my code:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var userId = $ionicUser.details.email;
var ref = firebase.database().ref().child('/users/' + userId);
$scope.users = $firebaseArray(ref);
}
but if my code is like that it works fine but display all the data from database:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var ref = firebase.database().ref().child( "users");
// create a synchronized array
$scope.users = $firebaseArray(ref);
}
Any help would be super appreciated.
inject $firebaseObject into the controller and then do
var ref = firebase.database().ref().child('/users/');
$scope.user = $firebaseObject(ref.child(userId));

Redirect only after $save success in AngularJS

I am POSTing a form and I want to redirect to my list page in case the form has no errors/is successfully persisted/saved to the db. How do I achieve that ?
app.controller('NoteCreateController',
['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
function($scope, Note, $routeParams, $location, ShareNoteScope) {
$scope.notes = ShareNoteScope.getScope().notes;
$scope.newNote = {};
$scope.createNote = function(note) {
var newNote = new Note(note);
newNote.$save(function(newNote) {
$scope.notes.unshift(newNote.note);
$scope.note = '';
$scope.errors = '';
}, function(newNote) {
$scope.errors = newNote.data;
// $location.path('/notes/'+newNote.note.id); where do I put this?
});
}
}]);
$save wraps success call with a callback. The piece of code above should do the trick.
newNote.$save(function (newNote) {
//success callback
$location.path('/notes/' + newNote.note.id);
}, function (newNote) {
$scope.errors = newNote.data;
});

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.

Sharing data between list view and detail view with angular

I would like create a simple e-commerce in angular, but i have a big problem.
How to create a list view and when i click on a item go to detail view with $params and data Service ?
Service
app.service("productService", function (filterFilter, $http, $routeParams) {
var items = [];
var promise = $http.get('process/product-view.php').then(function (res){
return items = res.data;
});
this.getProducts = function (){
return promise;
};
this.getProductAt = function(_name) {
return promise.then(function (res){
console.log(JSON.stringify(items));
return filterFilter(items, {
link_page: _name
})[0];
});
};
});
Controllers
shop
app.controller('shop', ['$scope', '$http', 'productService', function ($scope, $http, productService){
productService.getProducts().then(function (res){
$scope.products = res;
// console.log(JSON.stringify(res));
});
}]);
single-item
app.controller('single-item', ['$scope', '$routeParams', 'productService', function ($scope, $routeParams, productService){
$scope.product = productService.getProductAt($routeParams.item);
}]);
Thanks !

Resources