I have a situation where i am getting data on scroll from a service. Now i need to filter data using popular data and latest post
Here is my service:
App.factory('Serviec', function ($http, $rootScope) {
var Hututoo = function () {
this.items = [];
this.busy = false;
this.after = 'Serviec_0';
};
Serviec.prototype.nextPage = function () {
if (this.busy) return;
this.busy = true;
// return undefined
console.log($rootScope.listtype);
$http.get(baseurl + 'ajax/gethome?after=' + this.after).success(function (data) {
var items = data;
for (var i = 0; i < 5; i++) {
this.items.push(items[i]);
// debugger;
}
this.after = "Hututoo_" + this.items.length;
this.busy = false;
}.bind(this));
};
return Serviec;
});
In controller:
$scope.data= new Serviec();
$scope.listtype= 'latest';
$scope.changelist = function(str){
$rootScope.listtype = str;
$scope.data.items=[];
$scope.data.after = 'Serviec_0';
$http.post(baseurl+"ajax/gethome","after="+$scope.hututoo.after+"&list="+str).success(function(data){
$scope.data.items = data;
});
}
Html
<li ng-click="expression = 'latest';changelist('latest');" ng-class="{latest_icon:expression == 'latest'}">Latest Hoot</li>
<li ng-click="expression = 'popular';changelist('popular');" ng-class="{popular_icon:expression == 'popular'}">Popular Hoots</li>
So with these click i need to order data .I have to make http call to get data according to user click.
I was thinking that i can make a scope data that define listing type and get it in factory.
How can i inject this scope in Serviec Factory. I have tried it using rootscope. initally list type is set to latest , but it shows undefined. So what would be the best method achieve this?
Update:
Now i can access scope data in angular service, but small issue comes here is on list click previous item's in scope doesn't get empty and new items get pushed into the scope.
So demand is on list click previous data become zero and new get pushed into the scope.
Pass the $rootScope to controller and set the listtype as required.
App.controller('MainCtrl', function($scope, $rootScope, Hututoo) {
$scope.hututoo = new Hututoo();
$scope.listtype= 'latest';
$scope.changelist = function(str){
$rootScope.listtype= str;
$scope.hututoo = new Hututoo();
$scope.hututoo.nextPage();
}
});
Plunker
Avoid using $rootScope -- it's bad practice, much like using the head object in pure JS. You're already able to share data between the factory and controller, so why not just make listtype a property of the factory:
var Hututoo = function () {
...
this.listtype = 'latest';
};
and use it in your controller as you are other properties:
$scope.changelist = function(str){
$scope.hututoo.listtype = str;
...
};
Demo <-- ajax requests don't work for obvious reasons
$scope is not available to inject in services however you can pass it using parameters like so.
app.factory('Hututoo', function ($resource) {
var somePrivateVar = [];
return {
set: function(scopeVar){
somePrivateVar.push(scopeVar);
},
get: function(){
return somePrivateVar;
}
}
});
then in controller
Hututoo.set($scope.anyVar);
Related
I'm trying to pull data from an external JSON file and display it for the user to see. Through various actions, the user would then be able to change the data returned from the JSON file, without writing those changes to the file (in this example, incrementing values by one by clicking on a div). I've created a promise service that successfully pulls the data and displays it. I can even get it so the data can be changed in individual controllers.
This is where I get stuck: I cannot find a way to make any changes to the data in the PromiseService, so changes cannot propagate globally. How do I make it that any change in the promise data at the controller level will be reflected in the PromiseService and, thus, reflected in any data binding in the app? I'm new to promises, so I'm open to a completely different approach.
Plunker
HTML:
<body ng-app="pageApp" ng-controller="pageCtrl" nd-model="items">
{{items}}
<div class="button" ng-controller="buttonCtrl" ng-click="incrementValues()">
Click to increment:
<br>{{items}}
</div>
</body>
PromiseService:
pageApp.factory('PromiseService', function($http) {
var getPromise = function() {
return $http.get('items.json').then(function(response) {
return response.data;
});
};
return {
getPromise: getPromise
};
});
Button Controller (Page Controller in Plunker):
pageApp.controller('buttonCtrl', function($scope, PromiseService) {
$scope.incrementValues = function()
{
PromiseService.getPromise().then(function(data) {
$scope.items = data;
for(var i = 0; i < data.items.length; i++)
{
data.items[i]['value']++;
}
}).catch(function() {
});
};
});
The incrementValues function works successfully the first time, but each consecutive click re-pulls the promise and resets the data. To sum up: how do I reflect the incremented values in the PromiseService, as opposed to local variables?
You could add to your factory a private property where you store the items. Then create 3 different methods to update and access to that property.
pageApp.factory('PromiseService', function($http) {
var items = {}; // [] in case it is an array
var updateData = function(updatedData){
items = updatedData;
}
var getUpdateData = function(){
return items;
}
var getPromise = function() {
return $http.get('items.json').then(function(response) {
items = response.data;
return response.data;
});
};
return {
getPromise: getPromise,
updateData : updateData,
getUpdateData : getUpdateData
};
});
pageApp.controller('buttonCtrl', function($scope, PromiseService) {
$scope.items = [];
//You should call this method to retrieve the data from the json file
$scope.getData = function(){
PromiseService.getPromise().then(function(data) {
$scope.items = data;
}).catch(function() {
});
}
$scope.incrementValues = function(){
for(var i = 0; i < $scope.items.length; i++){
$scope.items[i]['value']++;
}
PromiseService.updateData($scope.items); //This could be skipped in case you do not want to 'store' these changes.
};
});
Then in others controller you could use the same service to retrieve the updated Data like this:
$scope.items = PromiService.PromiseService();
In the future you could also create a new method to update the json itself instead of stored internally
Your function creates a new $http call every time it's called, and thus returns a new promise, encspsulating new data, every time it's called.
You need to return the same promise every time:
var thePromise = $http.get('items.json').then(function(response) {
return response.data;
});
var getPromise = function() {
return thePromise;
};
I have a loading problem in Firebase. I want to display a list of images when I open the view but nothing happens till i go back ( there is a flash and i can see my photo list). It's working but not displaying in the opening.
What am i missing please ?
There is the beginning of my Controller view:
'Use Strict';
angular.module('App').controller('valider_photosController', function($scope, $state, $localStorage, Popup, Firebase, $firebaseObject, $ionicHistory, $ionicPopup, $ionicModal, $cordovaCamera) {
$scope.imagestab = [];
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');
ref_logements.child(id_logement).child('images').on('child_added', added);
function added(idxSnap, prevId){
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
console.log('La valeur'+datasnap.key+'donne '+datasnap.val());
});
};
});
Since firebase works with asynchronous calls, by the time firebase responds with your data the angular cycle had already finished and you won't have your scope updated. You can force it by using $scope.$apply();.
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
$scope.$apply();
});
There is a tool that integrates angular and firebase in a way that you won't have to be concerned with things such as applying the scope. Its called angularfire. I totally recommend you to start using it in your application.
With angularfire you can get your data simply using
$scope.bidule = $firebaseObject(ref_images.child(idxSnap.key));
or
$scope.images = $firebaseArray(firebase.database().ref('images'));
I created a Factory
.factory('Firebase', function ($firebaseArray, $firebaseObject) {
var ref = firebase.database().ref();
return {
all: function (section) {
var data = $firebaseArray(ref.child(section));
return data;
},
getById: function (section, id) {
var data = $firebaseObject(ref.child(section).child(id));
return data;
},
get: function (section, field, value) {
var data = $firebaseArray(ref.child(section).orderByChild(field).equalTo(value));
return data;
}
};
})
And then in my controller, i replaced like you said :
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');
ref_logements.child(index2).child('images').on('child_added', added);
function added(idxSnap, prevId) {
var monimage = Firebase.getById('images', idxSnap.key);
$scope.imagestab.push(monimage);
};
And it Works like a charm ! Thank you again :)
I'm trying angularjs for the first time and created a service that I use to make ajax calls to my application API and retrieve a paginated list. I called it "GridService". The service is injected into a controller and everything works great! Until I tried to use the same service twice inside two different controllers on the same page. To my horror, the second instance of the service overwrites the first (doh)
For example; I render two partials as follows :
<div id="location_areas" class="container tab-pane fade" ng-controller="areasController" ng-init="initialise()">
#include('areas._areas')
</div>
<div id="location_people" class="container tab-pane fade" ng-controller="peopleController" ng-init="initialise()">
#include('people._people')
</div>
and I inject the service into a controller as follows and link to the service properties
angular.module('areasController', [])
.controller('areasController', function($scope, $attrs, $http, AreaService, GridService, HelperService) {
$scope.areas = function() { return GridService.getListing() }
$scope.totalPages = function() { return GridService.getTotalPages() }
$scope.currentPage = function() { return GridService.getCurrentPage() }
$scope.columns = function() { return GridService.getColumns() }
Lastly, my abbreviated service is as simple as
angular.module('gridService', [])
.provider('GridService', function($http) {
var columns = {};
var filters = {};
var listing = [];
var totalPages = 0;
var range;
var currentPage = 1;
return {
/**
* Get the requested data (JSON format) from storage then populate the class properties which
* are bound to equivalent properties in the controller.
*
* #return void
*/
list : function(url,pageNumber,data) {
url = url+'?page='+pageNumber;
for (var key in data) {
if( angular.isArray( data[key] ) )
{
angular.forEach( data[key], function( value ) {
url = url+'&'+key+'[]='+value;
});
}
else
{
url = url+'&'+key+'='+data[key];
}
}
$http({ method: 'GET', url: url })
.then(function(response) {
listing = response.data.data;
totalPages = response.data.last_page;
range = response.data.last_page;
currentPage = response.data.current_page;
// Pagination Range
var pages = [];
for(var i=1;i<=response.data.last_page;i++) {
pages.push(i);
}
range = pages;
});
},
Obviously I have boobed (doh). Is it possible to create this scenario or have I misunderstood angularjs architecture?
Please update your question with the relevant code for your service. Services in Angular are by definition Singletons. They should not have any private state. If they do have state, it should be state that is means to be shared between two controllers.
If you are just making $http requests in your service, it should just return the promise to the calling controllers -- not causing any "overlap".
UPDATE
It looks like you a missing a few lines from your service. It looks like it contains columns, filters, etc.
So this is the problem, it is a singleton. What you should do it break it up into two different classes, the network layer that still makes the AJAX call to get the data -- and a factory that returns a new instance of your Grid configuration.
gridFactory.$inject = ['$http'];
function gridFactory($http) {
return function(url, pageNumber, data) {
// put your for (var key in data) logic here...
return new Grid($http);
}
}
function Grid($http) {
var self = this;
$http({ method: 'GET', url: url })
.then(function(response) {
self.listings = data.listings;
self.totalPages = data.total_pages;
...
// put your grid config here following this pattern, attaching each to
// the 'self' property which is the prototype of the constructor.
}
}
So now the factory will return a new instance of the 'Grid' object for every time you call the factory. You need to call the factory like gridFactory(url, pageNumber, data);
Folks:
I have 2 controllers, ctrlA and ctrlB - both unrelated to each other but are within the same page.
ctrlA queries an end point and returns a json object tags, which is then passed to a service method MyService.saveTags(tags) to store the object.
ctrlB then needs to populate a $scope variable $scope.tags by fetching the tags object created via ctrlA.
The service:
.factory('MyService', function($http, $q, $window) {
var myserviceFactory = {};
var savedTags = {};
// ..other methods..
myserviceFactory.saveTags = function(tags) {
if(!savedTags.tags){
console.log('saving tags..');
savedTags.tags = tags;
}
};
myserviceFactory.getSavedTags = function() {
console.log('returning tags..');
return savedTags.tags;
};
return myserviceFactory;
})
This issue appears to be ctrlB gets called first, so when $scope.savedTags = MyService.getSavedTags(); runs, it returns undefined.
Question: Angular n00b here - what would be the best way to fetch the tags after ctrlA has populated the object?
You can use a watch on the getSavedTags service method inside your ctrlB to know when is it populated. Something like
$scope.$watch(function() { return MyService.getSavedTags() },function(newValue) {
if(newValue) {
$scope.savedTags = newValue;
}
});
I have two controllers, to add Item and to delete Item, and a Model to show all items.
This model is injected into the controller ( on working on same template).
Whenever an item is added, I broadcast a message, which is listened by Model and it reloads the data from server.
Code:
ItemModule.factory('ItemListModal', function ($resource, $rootScope){
var allItem = $resource('item/page/:pageId.json', {'pageId': pageId });
var items = allItem.query();
$rootScope.$on('ItemAdded',function(){
items = allItem.query();
});
return items;
});
//Item is another Model, used to send data on server.
function CreateItemCtrl($scope, $rootScope, Item) {
$scope.save = function() {
Item.save($scope.item, function(data) {
$scope.result = data;
$rootScope.$broadcast('ItemAdded');
}, function(data) {
$scope.result = data.data;
});
}
}
function ListItemCtrl($scope, ItemListModal) {
$scope.allItems = ItemListModal;
}
Issue: Now since the dependency on ListItemCtrl is already resolved when template was first loaded, on adding Item it only changes the Model, but this is not re-injected into the ListItemCtrl. And due to this, the list on template do not change.
Is there any way to tell AngularJS to re-resolve the controller's dependency?
I really don't want to listen for event in Controllers and re-query data there, as there are other controllers which also needs same data from server.
Add another level of indirection on what you return from your service.
ItemModule.factory('ItemListModal', function ($resource, $rootScope){
var allItem = $resource('item/page/:pageId.json', {'pageId': pageId });
var data = {items:allItem.query()};
$rootScope.$on('ItemAdded',function(){
data.items = allItem.query();
});
return data;
});
function ListItemCtrl($scope, ItemListModal) {
$scope.allItems = ItemListModal;
// use as $scope.allItems.items wherever you need it. It will update when changes occur.
}
But it might be better to have a canonical representation of the item list on the client, and work to keep that current when you add things (just saving it to the server quietly).
The issue seems to be that while item is getting updated (have you tried console.log in the $on?) it's not an object and so hasn't been passed by reference. If you switch around your service to this:
ItemModule.factory('ItemListModal', function ($resource, $rootScope){
var ItemListModalScope = this;
var allItem = $resource('item/page/:pageId.json', {'pageId': pageId });
ItemListModalScope.items = allItem.query();
$rootScope.$on('ItemAdded',function(){
ItemListModalScope.items = allItem.query();
});
return ItemListModalScope;
});
And then wherever you use your allItems in your dome, you would do
{{ allItems.items }}