Hi,I was to fetch only the nodes where category = "Tribal" and return it as firebase array object.Thanks in advance.
Angular Service CODE:
this.getSpecialTourPackage = function(){
var dbRef = firebase.database().ref('states').child('itineraries');
return $firebaseArray(dbRef);
};
Angular Controller CODE:
if(_category != undefined && _category == 'Tribal'){
var loadedResult = [];
var resultArray = indiaTourService.getSpecialTourPackage();
resultArray.$loaded().then(function(data){
data.forEach(item =>{
loadedResult.push(item);
$scope.itineraries = _.where(loadedResult,{ category : "Tribal"});
});
});
}
Related
i am having a json response from which i wanted to create new json object
response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
i wanted to achieve this after manipulating keys and value pair
lang_Arr =[
{Reuters_ID:"Reuters ID"},
{parity_one:"Parity One"},
{parity_level:"Parity level"}
];
i have tried doing it in two ways
1) in this getting error as unexpected tokken (.)
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value.keyName:value.Detail});
});
2) here getting unxepected token [
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value['keyName']:value['Detail']});
});
i have tried assigning the values seperatly too but it doesn't work there also
var Lang_arr=[];
var k ='';
var v ='';
var i = 1;
angular.forEach(response, function(value, key) {
k ='';
v ='';
i = 1;
angular.forEach(value,function(val,key){
if(i == 1 )
k = val;
if(i == 2)
v = val;
if(!empty(k) && !empty(v))
Lang_arr.push({k:v})
i++;
});
});
You can use javascript map function to map the objects to array
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var lang_Arr =[];
lang_Arr = response.map(function(o){
var obj = {};
obj[o.Detail] = o.keyName;
return obj;
})
console.log(lang_Arr)
With Angular forEach also you can achieve this functionality
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var modifiedArray = [];
angular.forEach(response, function(val, key) {
var res = {};
res[val.keyName] = val.Detail;
this.push(res);
}, modifiedArray);
console.log(modifiedArray)
Working Example in Fiddle
You have to assign it in the http call that gets the response
$htpp.get(....).then(function(response){
lang_arr = [];
response.forEach(function(obj){
var item = {obj.keyName : obj.detail};
lang_arr.push(item);
}
This function is used to update and save the data into the firebase database. It's not working properly as I put the breaking at the save function, control doesn't enter the function. The changed data is reflected in the html but not in the firebase database.
$scope.editFormSubmit = function(){
console.log("Updating record");
//Get ID
var id = $scope.id;
console.log(id);
//Get Record
var rec = $scope.records.$getRecord(id);
console.log(rec);
//Assign Values
rec.fname = $scope.fname;
rec.lname = $scope.lname;
rec.mname = $scope.mname;
rec.email = $scope.email;
rec.company = $scope.company;
rec.phone = $scope.phone;
rec.city = $scope.city;
rec.state = $scope.state;
rec.zipCode = $scope.zipCode;
rec.conId = $scope.conId;
rec.DCN = $scope.DCN;
rec.jobTitle = $scope.jobTitle;
rec.pAddress = $scope.pAddress;
rec.country = $scope.country;
rec.name = $scope.name;
// Save Record
console.log("After assigning values");
console.log(rec);
$scope.records.$save(rec).then(function(){
console.log("Updating values");
});
clearFields();
//hide the edit form
$scope.editFormShow = false;
$scope.msg = "Contact Update";
}
Did you try
$scope.records.$save(rec).then(function(){
console.log("Updating values");
}, function(error) {
console.log(error);
});
I have a service that retrieves a JSON from an url, I use ng-repeat to show values in a list.
My JSON looks like this:
[
{"iconuser":"livingroom1","class":"w5","status":"0"},
{"iconuser":"meetingroom1","class":"w4","status":"1"}
]
How do I replace some values of that object.
example:
status = 0 should be status = OFF
status = 1 should be status = ON
In native angular:
$scope.item = [{"iconuser":"livingroom1","class":"w5","status":"0"},
{"iconuser":"meetingroom1","class":"w4","status":"1"}];
angular.forEach($scope.item,, function(obj) {
if(obj.status === 0)
obj.status = "OFF";
else
obj.status = "ON";
return obj;
});
You can use Array.map to format your response:
var formattedData = responseData.map(function(obj) {
if (obj.status === 0) {
obj.status = "OFF";
} //etc
return obj;
});
How can I count the number of data binds in my AngularJS application?
function getScopes(root) {
var scopes = [];
function traverse(scope) {
scopes.push(scope);
if (scope.$$nextSibling)
traverse(scope.$$nextSibling);
if (scope.$$childHead)
traverse(scope.$$childHead);
}
traverse(root);
return scopes;
}
var rootScope = angular.element(document.querySelectorAll("[ng-app]")).scope();
var scopes = getScopes(rootScope);
var watcherLists = scopes.map(function(s) { return s.$$watchers; });
_.uniq(_.flatten(watcherLists)).length;
Reference: http://larseidnes.com/2014/11/05/angularjs-the-bad-parts/
I'm trying to learn firebase/angularjs by extending an app to use firebase as the backend.
My forge looks like this
.
In my program I have binded firebaseio.com/projects to $scope.projects.
How do I access the children?
Why doesn't $scope.projects.getIndex() return the keys to the children?
I know the items are in $scope.projects because I can see them if I do console.log($scope.projects)
app.js
angular.module('todo', ['ionic', 'firebase'])
/**
* The Projects factory handles saving and loading projects
* from localStorage, and also lets us save and load the
* last active project index.
*/
.factory('Projects', function() {
return {
all: function () {
var projectString = window.localStorage['projects'];
if(projectString) {
return angular.fromJson(projectString);
}
return [];
},
// just saves all the projects everytime
save: function(projects) {
window.localStorage['projects'] = angular.toJson(projects);
},
newProject: function(projectTitle) {
// Add a new project
return {
title: projectTitle,
tasks: []
};
},
getLastActiveIndex: function () {
return parseInt(window.localStorage['lastActiveProject']) || 0;
},
setLastActiveIndex: function (index) {
window.localStorage['lastActiveProject'] = index;
}
}
})
.controller('TodoCtrl', function($scope, $timeout, $ionicModal, Projects, $firebase) {
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
var keys = $scope.projects.$getIndex();
console.log($scope.projects.$child('-JGTmBu4aeToOSGmgCo1'));
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("" + keys[0]);
});
// A utility function for creating a new project
// with the given projectTitle
var createProject = function(projectTitle) {
var newProject = Projects.newProject(projectTitle);
$scope.projects.$add(newProject);
Projects.save($scope.projects);
$scope.selectProject(newProject, $scope.projects.length-1);
};
// Called to create a new project
$scope.newProject = function() {
var projectTitle = prompt('Project name');
if(projectTitle) {
createProject(projectTitle);
}
};
// Called to select the given project
$scope.selectProject = function(project, index) {
$scope.activeProject = project;
Projects.setLastActiveIndex(index);
$scope.sideMenuController.close();
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
if(!$scope.activeProject || !task) {
return;
}
console.log($scope.activeProject.task);
$scope.activeProject.task.$add({
title: task.title
});
$scope.taskModal.hide();
// Inefficient, but save all the projects
Projects.save($scope.projects);
task.title = "";
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
$scope.toggleProjects = function() {
$scope.sideMenuController.toggleLeft();
};
// Try to create the first project, make sure to defer
// this by using $timeout so everything is initialized
// properly
$timeout(function() {
if($scope.projects.length == 0) {
while(true) {
var projectTitle = prompt('Your first project title:');
if(projectTitle) {
createProject(projectTitle);
break;
}
}
}
});
});
I'm interested in the objects at the bottom
console.log($scope.projects)
Update
After digging around it seems I may be accessing the data incorrectly. https://www.firebase.com/docs/reading-data.html
Here's my new approach
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
console.log(snapshot.val()['-JGTdgGAfq7dqBpSk2ls']);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
I'm still not sure how to traverse the keys programmatically but I feel I'm getting close
It's an object containing more objects, loop it with for in:
for (var key in $scope.projects) {
if ($scope.projects.hasOwnProperty(key)) {
console.log("The key is: " + key);
console.log("The value is: " + $scope.projects[key]);
}
}
ok so val() returns an object. In order to traverse all the children of projects I do
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
var keys = Object.keys(snapshot.val());
console.log(snapshot.val()[keys[0]]);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
Note the var keys = Object.keys() gets all the keys at firebaseio.com/projects then you can get the first child by doing snapshot.val()[keys[0])