How can I save data in forEach loop? - angularjs

I create a forEach loop. I can access data from Firebase with this loop and I can change variable. But I can not save these changes on Firebase. How can I save these changes? Here's my code:
var posts = $firebaseArray(ref);
posts.$loaded().then(function(item){
item.forEach(function(childSnapshot){
var num = childSnapshot.point-1;
childSnapshot.lastPoint = num;
});
});

You're using the AngularFire framework, which builds UI bindings on top of Firebase's regular JavaScript SDK. You should only be using it for things that you're binding to the Angular UI elements. For everything else, you're likely better off using Firebase's regular JavaScript SDK.
If I understand your requirement correctly, you're trying to loop over all child nodes in a database location once and modify a property. If so:
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var child = childSnapshot.val();
childSnapshot.ref().update({ lastPoint: child.point - 1 });
});
});
The relevant sections of the Firebase documentation are on reading data once and updating data.
Since AngularFire is built on top of Firebase's JavaScript SDK, they work perfectly together. So if elsewhere you bind the posts to the scope ($scope.posts = $firebaseArray(ref)), they will be updated automatically when you update the last point with the above snippet.

You can create a service that contains a getter and a setter. It would look something like this;
angular.module('app').factory("DataHandler",
function() {
var data;
return {
get: function() {
return data;
},
set: function(something) {
data = something;
}
}
}
);
Then in your code you would call:
var posts = $firebaseArray(ref);
posts.$loaded().then(function(item){
item.forEach(function(childSnapshot){
var num = childSnapshot.point-1;
childSnapshot.lastPoint = num;
DataHandler.set(childSnapshot);
});
});
Then wherever/whenever you need to get that data just call:
Datahandler.get();

Related

Getting data from a service always return the same value (not the updated) on AngularJs

i'm doing a crud like a phone list,
in a view i want to add persons to my list, and in another view i want to show that peoples,
for do that, i'm using two controllers, and a service to store my array with the persons.
to add peoples i'm using set way to pushing it to array when i click on a button and thats works fine(possible to see with console.log at salvar function in service).
My problem is, when i go to show the list with the get method after added some persons with set, the get method still returning my list like she starts (empty). how i can fix this?
angular
.module('moduloLista')
.factory('addMostrarService', addMostrarService);
function addMostrarService() {
var listacontatos = [
];
var salvar = function(obj){
listacontatos.push(obj);
};
var getLista = function(){
return listacontatos;
};
return{
salvar: function(obj){
salvar(obj);
},
getLista: function(){
return getLista();
}
}
}
^ Service Code
angular
.module('moduloLista')
.controller('testeController',testeController);
testeController.$inject = ['addMostrarService'];
function testeController(addMostrarService) {
var vm = this;
vm.dadoslista = addMostrarService.getLista();
console.log('vm.dadoslista');
}
^ controller to get the list from service.

How to set a variable in an AngularJS callback?

I have an AngularJS 1.5 directive:
var assetSearchService = function(proService) {
var assets = [];
var searchAssets = function(searchTerm){
proService.searchAssets(searchTerm).then(function(data){
assets = data.data;
});
};
return {
searchAssets, searchAssets,
assets: assets
};
};
When I try to use assetSearchService.assets in my controller after calling search, the data is not set in assetService.assets.
If I log the data after the searchAssets promise returns, I am getting data.
this.assets does not work so how do I do get the variable back from the callback?
Found an answer. Neither assets = newArray nor conact does not work because both return a new array and break the reference, rather than modifying the current one.
This works:
Array.prototype.push.apply(assets, data.data);
Here's a working example: https://jsfiddle.net/mbaranski/5k4bqo0z/
You can achieve more complex solution
var assetSearchService = function(proService) {
service = this;
service.assets = [];
service.searchAssets = function(searchTerm){
proService.searchAssets(searchTerm).then(function(data){
assets.push(data.data);
});
};
return service;
};

Firebase search with param?

so i just started with Firebase and AngularFire.
I've got this data structure:
friends
-JzKr-mrv-O7rlxrMi3_
creator: "111181498675628551375"
description: "dsa"
name: "das"
--JzKrahnTf47MXp8nAZx
creator: "111181498675628551320"
description: "ddasdassa"
name: "dasdadsadas"
Now i want to query with param creator = "111181498675628551320".
How can i do this ? I've tried this way:
.service('Friends', function ($firebase, store, $state) {
var friendsRef = new Firebase("url/friends");
friendsRef.authWithCustomToken(store.get('firebaseToken'), function (error, auth) {
if (error) {
// There was an error logging in, redirect the user to login page
$state.go('login');
}
});
var friendsSync = $firebase(friendsRef);
var friends = friendsSync.$asArray();
this.all = function () {
return friends;
};
this.getCreator = function(creator){
return friends.$getRecord(creator);
};
});
Anyone got maybe some dev reference how i should work with it?
Maybe i should make other call then url/friends?
AngularFire is a wrapper around the Firebase JavaScript SDK, which simplifies binding Firebase data to AngularJS views. When something is not obvious from the AngularFire documentation, refer to the Firebase JavaScript documentation.
You can read all about Firebase queries in the documentation. In that case what you'll need to do, is build the necessary query using Firebase's regular JavaScript SDK:
var ref = new Firebase('https://yours.firebaseio.com/friends');
var query = ref.orderByChild('creator').equalTo('111181498675628551320');
Then you can bind the resulting items to your view by using an AngularFire $firebaseArray():
$scope.friends = $firebaseArray(query);

How can I create custom GET urls with params using Backbone?

I've noticed that some web sites offer Ajax-ian search that refreshes the URL and displays the GET params used, for example:
someapp.com/search/Tokyo?price_min=80&price_max=300
As a result of an Ajax GET request.
I want to know how can I accomplish this by using Backbone.js, I understand that by using backbone's push state this may be possible, am I right?
How could I define a route like that (let's say the same case, scoped to /search) for a Place model for example?
Where would I do this? in a Router or in a Model?
I appreciate all the answers regarding this topic. And I apologize in advance for not providing any code, I usually do, but this exercise will be a proof of concept I'd like to make, and I hope backbone is the right tool for the job.
Thank you!
This is a working example of the solution - jsfiddle.net/avrelian/dGr8Y/, except that jsFiddle does not allow Backbone.history.navigate method to function properly.
Suppose, we have a button
<input class="fetch-button" type="button" value="Fetch" />​
and a handler
$('.fetch-button').click(function() {
Backbone.history.navigate('posts/?author=martin', true);
});
This is our collection of posts
var Posts = Backbone.Collection.extend({
url: 'api/posts'
});
This is our Router with a custom parameter extractor
var Router = Backbone.Router.extend({
routes: {
'posts/?:filters': 'filterPosts'
},
filterPosts: function(filters){
posts.fetch({data: $.param(filters)});
},
_extractParameters: function(route, fragment) {
var result = route.exec(fragment).slice(1);
result.unshift(deparam(result[result.length-1]));
return result.slice(0,-1);
}
});
It is simplified $.deparam analog. You could use your own instead.
var deparam = function(paramString){
var result = {};
if( ! paramString){
return result;
}
$.each(paramString.split('&'), function(index, value){
if(value){
var param = value.split('=');
result[param[0]] = param[1];
}
});
return result;
};
And finally, instantiation of posts collection and router object
var posts = new Posts;
var router = new Router;
Backbone.history.start();
When a user clicks on the button address bar changes to myapp.com/s/#posts?author=martin. Please, note the sign #. We use a hash query string. Of course, you can use push state, but it is not widespread yet.

using underscore variables with Backbone Boilerplate fetchTemplate function

I am building an application using the Backbone Boilerplate, and am having some trouble getting underscore template variables to work. I have a resource named Goal. My Goal View's render function looks like this:
render: function(done) {
var view = this;
namespace.fetchTemplate(this.template, function(tmpl) {
view.el.innerHTML = tmpl();
done(view.el);
});
}
I'm calling it inside of another view, like so:
var Goal = namespace.module("goal");
App.View = Backbone.View.extend({
addGoal: function(done) {
var view = new Goal.Views.GoalList({model: Goal.Model});
view.render(function(el) {
$('#goal-list').append(el);
});
}
});
I'm using local storage to save my data, and it's being added just fine. I can see it in the browser, but for some reason, when I load up the app, and try to fetch existing data, i get this error:
ReferenceError: Can't find variable: title
Where title is the only key I'm storing. It is a direct result of calling:
tmpl();
Any thoughts are greatly appreciated.
Your template is looking for a variable title, probably like this <%- title %>. You need to pass it an object like this tmpl({ title: 'Some title' })
Turns out, I wasn't passing in the model when i created the view, which was making it impossible to get the models data. Once I passed in the model correctly, I could then pass the data to tmpl, as correctly stated by #abraham.
render: function(done) {
var
view = this,
data = this.model.toJSON();
clam.fetchTemplate(this.template, function(tmpl) {
view.el.innerHTML = tmpl(data);
done(view.el);
});
},

Resources