Firebase retrieve data shows only one result - angularjs

I am trying to retrieve a data of objects and the result shows on the console but it only shows one result(the last result) on the page.
$http.get('/users').success(function(data) {
$scope.username = data; //assign data to username
console.log(data);
});
And in my Jade template, i have
section(data-ng-controller='browse')
h4 hi
ul(data-ng-repeat='user in username')
li {{user}}
I want to loop through this data
{
"google: xxxxxxxxxxxxx" : {
"name" : "ZZZ YYY",
"profile" : {
"briefProfile" : "Cost call",
"career" : "Web Developer",
"projects" : {
"-JjtSgiwkqFxTxMv0Gip" : "http://zipper.com"
}
},
"provider" : "google"
},
"google:xxxxxxxxxxx" : {
"name" : "SSS TTT",
"profile" : {
"briefProfile" : "Desired Intelligence",
"career" : "Consultant"
},
"provider" : "google"
}
}
Thanks.(i'm not using angularFire).

If you're using the $http service, then you're not using Firebase.
You are repeating the ul instead of the li. Also, {{user}} will be the whole user object, and you will see something like [Object object] on your page instead of a string. So call {{user.name}}.
ul
li(data-ng-repeat='user in users') {{user.name}}
Assuming that $http is there by mistake, and you meant to use Firebase instead, you probably want to start by reviewing the Firebase Getting Started guide
// Get a reference to users
var ref = new Firebase('https://<YOUR-FIREBASE>.firebaseio.com/users');
// Attach an asynchronous callback to read the data at users ref
ref.on("value", function(snapshot) {
console.log(snapshot.val());
$scope.users = snapshot.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});

If you're using AngularFire you should take a look at this:
Instead of using $http.get try:
var data = $firebaseArray(new Firebase("URL"));
$scope.data = data;
Don't forget to add $firebaseArray as a dependency in your controller.
More info on AngularFire docs:
https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray
If you're not using AngularFire take a look at this:
var firebaseRef = new Firebase('YOUR-FIREBASE-URL/users/');
firebaseRef.on('value', function(dataSnapshot) {
var data = dataSnapshot.val();
console.log(data);
$scope.users = data;
// Might need to use $digest to update $scope.
$scope.$digest();
});
More about on() in Firebase docs:
https://www.firebase.com/docs/web/api/query/on.html

Related

update the json after delete some data inside it

I try to learn angular. currently, i already get data from JSON ( i use local JSON). I try to delete 1 of an array from JSON, its works but after I refresh the page the deleted array come back again. how to update the JSON after I delete array?
customer.html
<tr ng-repeat="experience in experiences">
<td>{{experience.no}}</td>
<td>{{experience.name}}</td>
<td><button ng-click="deleteItem(experience)" class="btn btn-danger">-</button></td>
</tr>
main.js
resolve:{
experiences:['$http',function($http){
return $http.get('scripts/customer.json').then(function(response){
return response.data
})
}]
}
customer json
[
{
"no":1,
"name": "Sarah",
},
{
"no":2,
"name": "Tommy",
}
]
customerCtrl.js
angular.module('app').controller('customerCtrl',['$scope','experiences',function($scope,experiences){
$scope.experiences= experiences;
$scope.deleteItem =function(experience){
var index = $scope.experiences.indexOf(experience);
alert("Deleting DATA: "+ index);
$scope.experiences.splice(index,1);
};
}]);
You're trying to store data in a file using javascript, which is considered as insecure and then hard to implement.
I would suggest you to use LocalStorage instead. Here is a service example you could use in your controller (not tested)
localstorage service
angular.module('app').service('LocalStorage', function(){
return {
save: function(data) {
localStorage.setItem('data',data);
},
get: function(){
return localStorage.getItem('data');
}
};
});
controller
// notice that I injected LocalStorage in controller
angular.module('app').controller('dataPengalamanCtrl',['$scope','experiences',function($scope,experiences, LocalStorage){
$scope.experiences= experiences;
$scope.deleteItem =function(experience){
var index = $scope.experiences.indexOf(experience);
alert("Deleting DATA: "+ index);
$scope.experiences.splice(index,1);
// First transform you're json to a string
var stringifiedData = JSON.stringify( $scope.experiences);
// from there we save data to localStorage
LocalStorage.save(stringifiedData );
};
// if you need, you can load data using :
$scope.data = LocalStorage.get();
Dont forget to save your json in localstorage first, for example with a file like this one :
init.js
var json = [
{
"no":1,
"name": "Sarah",
},
{
"no":2,
"name": "Tommy",
}
];
var strData = JSON.stringify(json);
localstorage.setItem('data', strData);
EDIT
If you want to go with a remote server like myjson.com
Assuming you already saved your json on myjson.com, and url is https://api.myjson.com/bins/8hghd then :
To retrieve your json use $http.get('https://api.myjson.com/bins/8hghd').success(/*...*/).error(/*..*/);
To update your json use $http.put with your json as data (grammar depending of your AngularJS version, see here)
Have a look to the api documentation : http://myjson.com/api

AngularJS binding not occurring on page until a user action

I've got my first angular app which displays some data from a list via ng-repeat.
The controller for the view sets a few variables to scope - some directly in the function and another from an API call.
The data from the in function load is showing up in that ng-repeat. The data from the service call doesn't show up (debugging shows the function is being called and data returned and set in scope).
I've got a filter on and if I type anything in it then the data shows up. Or when I click to another view the data flashes onto the page briefly before it loads the new view.
Here is some view code (the items works, venues does not):
<div ng-repeat="item in items">
{{ item.firstName }}
</div>
<div ng-repeat="venue in venues">
{{ venue.details }}
</div>
And here is the controller (data is coming back from the call):
$scope.items = [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
];
var client = new WindowsAzure.MobileServiceClient("url", "key");
var query = client.getTable("venues").read().done(function (results) {
$scope.venues = results;
}, function (err) {
alert("Error: " + err);
});
I'm wondering if maybe the binding is happening before the data is returned from the API?
I added a div and this line into the function and it is printing the results to the page no issues:
document.getElementById("venueslist").innerHTML = JSON.stringify(results);
Thank you for reading.
Looking at your code client.getTable doesn't look like it is using any of angularJs $http or $timeout service. So you will have to wrap the assignment in scope.$apply() so that the $digest cycle is run and the bindings are updated in the view.
var query = client.getTable("venues").read().done(function (results) {
$scope.$apply(function () {
$scope.venues = results;
});
}, function (err) {
alert("Error: " + err);
});
Side note: why are you doing JSON.parse(JSON.stringify(results)), you can directly use results if it is a json object.

Loading Backbone model by custom attribute

Lets say, I have the following Backbone model :
var Meal = Backbone.Model.extend({
defaults: {
"appetizer": "caesar salad",
"entree": "ravioli",
"dessert": "cheesecake"
},
urlRoot : api/meals,
idAttribute : id,
// some other stuff
});
Assuming that I have a backend Spring MVC conroller that intercept GET requests, so when I fetch my model, using
myMeal.fetch();
my model gets loaded from the server.
for now everything is clear, my question is, what if I have another method on the backend that takes a string as parameter and return as responsebody, the right json element.
how can I make that call from my model ?
I'm looking for something like this :
var meal = new Meal({'entree': 'value'});
meal.fetch({
// if there is no id, and 'entree' is given, I want to call /
// api/findByEntree passing this.entree as parameter.
});
I want to make an Ajax call from the object itself to the backend, by specifying the url inside the Backbone model.
urlRoot can be a function so no need to override fetch. I believe you could just do something like this:
var Meal = Backbone.Model.extend({
defaults: {
"appetizer": "caesar salad",
"entree": "ravioli",
"dessert": "cheesecake"
},
urlRoot : function() {
return 'api/' + this.get('id') ? 'meals' : 'findByEntree';
},
idAttribute : id,
// some other stuff
});
You can override the default fetch, intercept the call, do some verification and then pass onto the original fetch:
var Meal = Backbone.Model.extend({
fetch: function(options) {
if(this.has('id')) {
Backbone.Model.prototype.fetch.call(this, options);
} else {
this.findByEntree(options);
}
},
fetchByEntree: function(options) {
...
}
});
however, keep in mind that you'll need some extra logic to deal with the case of trying to fetch a new Meal, which won't have neither id nor entree.

WebSQL data into AngularJs DropDown

I have very simple question about getting data from WebSql
I have DropDown i.e
<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
ng-init="foodCatagory = foodCatagories.cast[0]"
ng-options="foodCatagory as foodCatagory.text for foodCatagory in foodCatagories.cast"
ng-model="foodCatagory"
ng-change="changeFoodCatagory()">
</select>
now i want to add data init from webSQL. I already get Data from webSql but i am confuse that how to add that data into DropDown
An example or hints maybe very helpful for me.
Update 1 :: Add Controller Code
myApp.controller('foodSelection',function($scope,foodCatagories){
$scope.foodCatagories = foodCatagories;
$scope.changeFoodCatagory = function(){
alert($scope.foodCatagory.value);
}
});
Update 2 webSQL and JayData
_context.onReady({
success: showData,
error: function (error){
console.log(error);
}
});
function showData(){
var option = '';
_context.FoodGroup.forEach(function(FG)
{
option += '<option value="'+FG.FoodGroupID+'">'+FG.Description+'</option>';
}).then(function(){
console.log(option);
});
}
Update 3
var myApp = angular.module('myApp',[]);
myApp.factory('foodCatagories',function(){
var foodCatagories = {};
foodCatagories.cast = [
{
value: "000",
text: "Select Any"
}
];
return foodCatagories;
});
Update 4
One thing that i didn't mention is that I am using JayData for getting data from webSQL to my App
I will try to explain how it works:
EDIT: Live demo
html
Here is your stripped down select.
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
The directive ng-options will fill automatically the option elements in your select. It will take the foodCategories variable from the $scope of your controller and foreach item in the collection, it will use the text property as the label shown (<option>{{item.text}}</option>') and it will select the whole objectitemas the value of the selectedoption. You could also refer to a property as the value like ({{item.text}}). Then yourng-modelwould be set to theid` value of the selected option.
The directive ng-model corresponds to the variable in the $scope of your controller that will hold the value of the selected option.
The directive ng-required allows you to check if a value has been selected. If you are using a form, you can check if the field is valid formName.ngModelName.$valid. See the docs for more details on form validation.
The directive ng-change allows you to execute a function whenever the selected option changes. You may want to pass the ng-model variable to this function as a parameter or call the variable through the $scope inside the controller.
If no default value is set, angular will add an empty option which will be removed when an option is selected.
You did use the ng-init directive to select the first option, but know that you could set the ng-model variable in your controller to the default value you would like or none.
js
Here I tried to simulate your database service by returning a promise in the case that you are doing an async request. I used the $q service to create a promise and $timeout to fake a call to the database.
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
In your controller you set the variables that will be used in your view. So you can call your DbFoodCategories service to load the data into $scope.foodCategories, and set a default value in $scope.foodCategory that will be used to set the selected option.
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
I hope that this helped you understand more in detail what is happening!
See this example and how use $apply to update the data in scope.
in the new version we released a new module to support AngularJS. We've started to document how to use it, you can find the first blogpost here
With this you should be able to create your dropdown easily, no need to create the options manually. Something like this should do the trick:
myApp.controller('foodSelection',function($scope, $data) {
$scope.foodCatagories = [];
...
_context.onReady()
.then(function() {
$scope.foodCatagories = _context.FoodGroup.toLiveArray();
});
});
provided that FoodGroup has the right fields, of course

Backbone.js - custom collection not working

In the backbone.js, for the purpose of filtering the data, i am fetching by click the element.
and i am saving the collection as newcollection. but i unable to get any data.
what is wrong with my code...
my code :
taskListPhraseI.collection = Backbone.Collection.extend({ // collection fetching
model:taskListPhraseI.model,
url : 'data/data.json',
});
taskListPhraseI.allView = Backbone.View.extend({
el:$('.boardHolder'),
events:{
'click span.green' : 'filterIt'
},
initialize:function(){
var that = this;_.bindAll(this);
this.collection = new taskListPhraseI.collection(); //initial stage i am fetching
this.collection.fetch({success:that.render});
this.on('change:filterType', this.setNewType); //on click trigger my custom method to get the collection again
//this.on('reset:filterType', this.setNewType);
},
setNewType:function(){
var newCollection = new taskListPhraseI.collection(); // my custom collection
newCollection.fetch(); // fetching
this.collection.reset(newCollection,{ silent: true }) // triggering rest
var filterType = this.filterType,
filtered = _.filter(this.collection.models, function (item) {
return item.get("dueDays") === filterType;
});
console.log(newCollection.models); // not working... why?
console.log(this.collection.models);// works
this.collection.reset(filtered);
},
or the way i am doing wrong.. to filter the collection
any one guide me a correct way of process...
thanks in advance
fetch is async. Execute your code after collection will be fetched
newCollection.fetch({context:this}).done(function() {
// your code
})
Plus this is not correct reset method usage:
this.collection.reset(newCollection,{ silent: true })
Use this way:
this.collection.reset(newCollection.toJSON(), {silent:true})
EDIT (Added example)
HTML
<button>change filter</button>
JS
var url1 = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=vpetrychuk&count=9'
var url2 = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=derickbailey&count=9'
var collection = new (Backbone.Collection.extend({
url : url1,
resetWithFilter : function(key, value) {
var query = {};
query[key] = value;
this.reset(this.where(query));
}
}));
// fetch initial data
collection.fetch({dataType:'jsonp'});
$(':button').on('click', function() {
// change url and fetch another data
collection.url = url2;
collection.fetch({dataType:'jsonp'}).done(function(response) {
console.log('items count before filter:', collection.length);
// now reset collection with selected filter
collection.resetWithFilter('id_str', '294429621640912896');
console.log('items count after filter:', collection.length)
});
});
Fiddle: http://jsfiddle.net/vpetrychuk/N4ZKm/

Resources