Updating icon in real tme in Ionic - angularjs

I have a favourites icon that should change from an outline to solid but it will only do this once the page has been reloaded. Is there any way to update this in real time without reloading the page.
It should update the ng-class to change from an outline to solid.
<i ng-class="{'icon ion-android-star': favicon(office.id), 'icon ion-android-star-outline': !favicon(office.id)}"
ng-click="togglefav(office.id); $event.stopPropagation();"></i>
This checks if the value is in local storage, then returns true or false.
.controller('APICtrl', function($scope, $http, $localstorage, $window, $state, $sce) {
// Search function
$scope.query = {}
$scope.queryBy = '$'
// gets the data from offices.json
$http.get('js/offices.json').then(function(resp) {
console.log('Success', resp);
$scope.offices = resp.data.office;
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
});
$scope.sce = function(loc1){
return $sce.trustAsHtml("https://www.google.com/maps/geocoding/json?address=loc1&key=AIzaSyBGAHnplGPjFoVvShk6Tsna3-DN8rHQBI8")
}
//retrieves localstorage array
//$scope.favourties= JSON.parse($window.localStorage['fav']);
//$scope.favourites = $window.localStorage['favs'] ? JSON.parse($window.localStorage['favs']) : []
//checks if the array if is in localstorage, if it isnt then it adds an array, if it is it parses the array
if($window.localStorage['fav']){
$scope.favorites = JSON.parse($window.localStorage['fav']);
var fav = JSON.parse($window.localStorage['fav']);
} else {
var fav = [];
$window.localStorage['fav'] = JSON.stringify(fav);
}
console.log(fav);
$scope.togglefav = function(id) {
//checks if the id being passed in is already in the array
//if it isn't it will add it to the beginning array then stringify it
if (fav.indexOf(id) == -1){
fav.unshift(id);
console.log(fav);
$window.localStorage['fav'] = JSON.stringify(fav);
}
//if it is then it will remove it from the array and stringify the array
else{
fav.splice(fav.indexOf(id), 1);
$window.localStorage['fav'] = JSON.stringify(fav);
console.log(fav);
}
}
//last viewed office view
if($window.localStorage['last']){
$scope.favorites = JSON.parse($window.localStorage['last']);
var last = JSON.parse($window.localStorage['last']);
} else {
var last = [];
$window.localStorage['last'] = JSON.stringify(last);
}
console.log(last);
$scope.lastview = function(id) {
//checks if the id being passed in is already in the array
//if it isn't it will add it to the beginning array then stringify it
var c = JSON.parse($window.localStorage['last']);
if (last.indexOf(id) == -1){
if (c.length > 3){
last.pop();
}
last.unshift(id);
$window.localStorage['last'] = JSON.stringify(last);
}
}
// used to change the favourites icon based on if its in the local storage or not
var e = JSON.parse($window.localStorage['fav']);
$scope.favicon = function(office){
return e.indexOf(office) !== -1;
};
// used to check if the item is in localstorage and check it against the json array
// if it matches then it will return true and be displayed
// this one is used for favourited offices
$scope.ifinfav1 = function(office){
return e.indexOf(office.id) !== -1;
};
var f = JSON.parse($window.localStorage['last']);
// this one is used for last viewed offices
$scope.ifinfav2 = function(office){
return f.indexOf(office.id) !== -1;
};
})

(function(angular) {
'use strict';
angular.module('includeExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', '$q',
function($scope, $q) {
$scope.office = {
id: 'here'
};
//var e = JSON.parse($window.localStorage['fav']);
var e = ['here']
$scope.favicon = function(office) {
return e.indexOf(office) !== -1;
};
$scope.togglefav = function(office) {
if ($scope.office.id === 'here')
$scope.office.id = 'here2';
else
$scope.office.id = 'here';
};
}
]);
})(window.angular);
.ion-android-star{
color:red;
}
.ion-android-star-outline{
color:blue;
}
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-animate.js"></script>
<body ng-app="includeExample">
<div ng-controller="ExampleController">
<i ng-class="{'icon ion-android-star': favicon(office.id), 'icon ion-android-star-outline': !favicon(office.id)}" ng-click="togglefav(office.id); "> Content</i> (click me)
</div>
</body>
you can use the $scope in office variable.
when you change the office will be visible to the template as well.

Related

How to check string in json array

console.log($scope.filteredOffers);hi to all want to check string in json like that string coming form params now want to check in whole json and display only data which is related to that . Kindly check my code .. in other words want to display data according to the params which is coming form url (which is coming ).
.controller('mixCtrl', function($scope,$http,$stateParams) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.myData = response.data;
$scope.offerName = ''; //set initially
$scope.selectedIndex = -1;
$scope.filteredOffers = [];
// $scope.link1 = [];
$scope.da = $stateParams.offer_name;
var a = $scope.da;
console.log(a);
$scope.filteredOffers = $scope.myData.filter(function(a) {
for (var i=0;i<$scope.myData.length;i++)
{
$link =$scope.myData[i].offer_name;
if (a==$link)
{
return a ;
console.log(a );
}
//console.log(a );
}
// return offer.offer_name == $scope.da;
console.log($scope.da);
});
});
/*
$scope.showData = function(offer_name, index) {
$scope.offerName = offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
$scope.selectedIndex = index;
}*/
$scope.dealopen = function(a){
for (var i=0;i<$scope.myData.length;i++)
{
//console.log($scope.data[i].name);
$link=$scope.data[i].name;
console.log($link);
if ($link==$a)
{
$window.open($link,"_self","location=yes");
//console.log($a);
}
}
}
})
Html
<div ng-repeat="offer in filteredOffers">
<div class="couponCode">{{offer.coupon_code}}</div>
<div class="couponTitle">{{offer.coupon_title}}</div>
<div class="couponDescription">{{offer.coupon_Description}}</div>
</div>
You are use the Array.filter() function wrongly!
Before :
$scope.filteredOffers = $scope.myData.filter(function(a) {
for (var i=0;i<$scope.myData.length;i++)
{
$link =$scope.myData[i].offer_name;
if (a==$link)
{
return a ;
console.log(a );
}
//console.log(a );
}
// return offer.offer_name == $scope.da;
console.log($scope.da);
});
After (According to correct syntax) :
$scope.filteredOffers = $scope.myData.filter(function(a) {
if (check condition)
{
return true ;// when true is returned the json held in a gets pushed into the filteredOffers array
}
else{
return false;//when false is returned, the json held in 'a' is ignored and not pushed into the filteredOffers array
}
});
Array.filter's Doc Link
But there is something wrong with the logic that you have used. If you can tell me exactly what you are trying to do, I might be able to help you out.
If you are processing json and arrays frequently in your application, then it's better to integrate loadash or underscore in you application.
Add below code to your HTML before loading the controller file.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
After looking the response of http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8, below code will give you the array that matches the offer_name.
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.filteredOffers = [];
var offerName = $stateParams.offer_name;
$scope.filteredOffers = _.filter(response.data, ["offer_name",offerName]);
})

Switch between 2 ng-shows

I have two elements with a ng-show in them,
%a.follow{"ng-click" => "followUser(user)", "ng-show" => "!isFollowed(user.id)"} follow
%a.unfollow{"ng-click" => "unfollowUser(user)", "ng-show" => "isFollowed(user.id)"} unfollow
It depends on the user.id which ng-show is being rendered in the template. So only one of the two ng-shows is displayed.
So for example a user wants to start following another user. Then the follow link is displayed.
%a.follow{"ng-click" => "followUser(user)", "ng-show" => "!isFollowed(user.id)"} follow
When a user clicks on it, I would like to hide the clicked ng-show, and show the unfollow ng-show so that the user can unfollow the just followed user.
The follow and unfollow user function,
$scope.followUser = function (user) {
followUser.create({
followed_id: user.id
}).then(init);
Notification.success(user.name + ' is toegevoegd als vriend.');
}
$scope.unfollowUser = function(user){
unfollowUser.unfollowUser(user).then(function(){
},function(){
}).then(init);
Notification.success(user.name + ' is verwijderd als vriend.');
}
And the isFollowed function,
usersService.loadUsers().then(function(response) {
$scope.users = response.data;
console.log ($scope.users)
angular.forEach(response, function(user){
$scope.user = user
$scope.isFollowed = function(userId) {
var following = $scope.current_user.following;
for (var i=0; i<following.length; i++) {
if (following[i].id == userId) {
return true;
}
}
return false;
}
})
})
I've tried building this,
<a ng-click="follow=false ;unfollow=true", ng-show="follow">Follow!</a>
<a ng-click="follow=true; unfollow=false", ng-show="unfollow">Unfollow!</a>
This does switch between the two ng-shows, but when I try to get the isFollowed(user.id), !isFollowed(user.id) in them the code crashes.
You should create single function to follow/unfollow, Here in the code snippet I have introduced a new property i.e. isFollowed to object user whose value is set using the isFollowed function.
Additionally, Don't overuse isFollowed(user.id) method, it will be huge performance hit.
HTML
<a ng-click="followUnfollowUser(user)"> {{ user.isFollowed : "Unfollow!" : "Follow!"}} </a>
Script
$scope.followUnfollowUser = function(user) {
//If followed - unfollow
if (user.isFollowed) {
unfollowUser.unfollowUser(user).then(function() {
user.isFollowed=!user.isFollowed
}, function() {
}).then(init);
Notification.success(user.name + ' is verwijderd als vriend.');
} else {
followUser.create({
followed_id: user.id
}).then(function() {
user.isFollowed=!user.isFollowed
}, function() {
}).then(init);
Notification.success(user.name + ' is toegevoegd als vriend.');
}
}
//Define method to check wheather current user is beign followed
var isFollowed = function(userId) {
var following = $scope.current_user.following;
for (var i = 0; i < following.length; i++) {
if (following[i].id == userId) {
return true;
}
}
return false;
}
//Fetch Users
usersService.loadUsers().then(function(response) {
$scope.users = response.data;
//Iterate and create isFollowed property
angular.forEach($scope.users, function(user) {
user.isFollowed = isFollowed(user.id);
})
})
Note: I'm not familiar with following syntax thus used standard HTML.
%a.follow{"ng-click" => "followUser(user)", "ng-show" => "!isFollowed(user.id)"} follow
Alrhgout Satpal did point me to the right direction and helped me with some code. His answer isn't complete. So I've decided that add the code I'm using for this function (made with the help of Satpal!).
I've created a followUnfollowUser function. But instead of having two .then(init) I have one init() at the end of the function. Having the two inits gave me some looping trouble.
$scope.followUnfollowUser = function(user) {
//If followed - unfollow
if (user.isFollowed) {
unfollowUser.unfollowUser(user).then(function() {
user.isFollowed=!user.isFollowed
}, function() {
})
Notification.success(user.name + ' is verwijderd als vriend.');
} else {
followUser.create({
followed_id: user.id
}).then(function() {
user.isFollowed=!user.isFollowed
}, function() {
})
Notification.success(user.name + ' is toegevoegd als vriend.');
}
init();
}
Then the init function,
var init = function () {
loadCurrent_user.loadCurrent_user().then(function(response) {
$scope.current_user = response.data;
});
usersService.loadUsers().then(function(response) {
$scope.users = response.data;
//Iterate and create isFollowed property
angular.forEach($scope.users, function(user) {
user.isFollowed = isFollowed(user.id);
})
})
var isFollowed = function(userId) {
var following = $scope.current_user.following;
for (var i = 0; i < following.length; i++) {
if (following[i].id == userId) {
return true;
}
}
return false;
}
}
First I load the current user so that the $scope.current_user gets updated when a user is being followed/unfollowed. And then I iterate through each user and create the isFollowed value using the isFollowed function.
And in my template I have,
%a{"ng-click" => "followUnfollowUser(user)"}
-# {{ user.isFollowed }}
{{ user.isFollowed ? "Unfollow user" : "Follow user"}}

angularjs Ionic and global variables: best practice to make a variable available globally

I am new to Angular/Ionic.
Before using Angular/Ionic, at the launch of my app, I was checking if we were under Phonegap or a browser using and storing this information in a global boolean variable and then checking if the app was online or offline and storing it to a global variable too, like this :
var isPhoneGap;
var connectionStatus;
isPhoneGap = checkIfPhoneGap();
//later in the code :
connectionStatus = checkIfOnline();
function checkIfPhoneGap() {
var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
if ( app ) {
return true;
} else {
return false;
}
}
function checkIfOnline() {
if ( isPhoneGap ) {
if (checkConnection() == "none" ) {
connectionStatus = 'offline';
} else {
connectionStatus = 'online';
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
//console.log('Connection : ' + Connection);
//console.log('Connection type: ' + states[networkState]);
return networkState;
}
} else {
connectionStatus = navigator.onLine ? 'online' : 'offline';
}
return connectionStatus;
}
Now I would like to do the same with Angular/Ionic, I understand that I have to use a "Service". But is it the best way to make this information available through all the code ?
I am doing the following, but is it the "best practice" ?
in index.html :
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
in services.js :
angular.module('SnowBoard.services', [])
.factory('isPhoneGap', function() {
var appp = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
if ( appp ) {
return true;
} else {
return false;
}
})
;
in app.js :
angular.module('SnowBoard', ['ionic', 'SnowBoard.controllers', 'SnowBoard.services'])
.run(["isPhoneGap","$ionicPlatform", function(isPhoneGap, $ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
//CHECK IF ONLINE
connectionStatus = checkIfOnline(isPhoneGap);
//DEBUG
//var debugOptionUseLocalDB=0;
//updateProDB(connectionStatus, debugOptionUseLocalDB);
}])
.config(function($stateProvider, $urlRouterProvider) {
//...all state configurations
})
.config(function($stateProvider, $urlRouterProvider) {
//...
});
This works for now, but I need the boolean isPhoneGap to be available everywhere I need it (almost everywhere in my app).
Can you converge to the best practice to do this ?
Thanks
You should not set variables using $rootScope, and try to refrain from using $scope as much as possible. Using LocalStorage is okay, but this data will persist. I would recommend setting up a factory to store and retrieve variables using SessionStorage. SessionStorage is tied to the tab you have open, so the data is gone when it is closed.
This is one of my session storage services. I throw $cookieStorage in case local storage isn't available. Also, localStorage can only store strings. This is why you will see me converting objects and arrays to and from JSON as needed. After injecting sessionService, I need only call sessionService.store(name, data) to store a session variable or sessionService.persist(name, data) to store persistent data i.e. userName if "Remember Me" is checked. :
.service('sessionService', ['$cookieStore', function ($cookieStore) {
var localStoreAvailable = typeof (Storage) !== "undefined";
this.store = function (name, details) {
if (localStoreAvailable) {
if (angular.isUndefined(details)) {
details = null;
} else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) {
details = angular.toJson(details);
};
sessionStorage.setItem(name, details);
} else {
$cookieStore.put(name, details);
};
};
this.persist = function(name, details) {
if (localStoreAvailable) {
if (angular.isUndefined(details)) {
details = null;
} else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) {
details = angular.toJson(details);
};
localStorage.setItem(name, details);
} else {
$cookieStore.put(name, details);
}
};
this.get = function (name) {
if (localStoreAvailable) {
return getItem(name);
} else {
return $cookieStore.get(name);
}
};
this.destroy = function (name) {
if (localStoreAvailable) {
localStorage.removeItem(name);
sessionStorage.removeItem(name);
} else {
$cookieStore.remove(name);
};
};
var getItem = function (name) {
var data;
var localData = localStorage.getItem(name);
var sessionData = sessionStorage.getItem(name);
if (sessionData) {
data = sessionData;
} else if (localData) {
data = localData;
} else {
return null;
}
if (data === '[object Object]') { return null; };
if (!data.length || data === 'null') { return null; };
if (data.charAt(0) === "{" || data.charAt(0) === "[" || angular.isNumber(data)) {
return angular.fromJson(data);
};
return data;
};
return this;
}])
$cookieStore is part of ngCookies. Make sure you have angular-cookies.js included and load ngCookies as you would any module. Angular ngCookies
First off, I'm pretty new to both Ionic and Angular, however I had the same problem with my web app Angular and I have done following to get it working
assign variables to $rootScope, that way it's visible to all the controllers
assign variables to $scope , which is visible by current context. Ex: controller and the html pages uses that controller
localStorageService, because this will hold the values even after user refreshes the page.
Again please note, this is what I did in my Angular web app and might not be the best practices, but I hope you get the idea.
There are methods available in ionic.Platform that assist in getting back the data you need in regards to the device type.
http://ionicframework.com/docs/api/utility/ionic.Platform/
You could alternatively look at adding ngCordova, which has a bunch of useful wrappers around cordova plugins, including the device plugin.
http://ngcordova.com/docs/#Device

Sorting elements in an AngularFire array using a filter

I use Angular with Firebase and now stuck with error when trying to make a factory to work with filter.
app.factory('itemsFactory', ["$scope", '$rootScope', "$firebase", "simpleLogin",
function($scope, $rootScope, $firebase, simpleLogin) {
var ref = new Firebase("https://------.firebaseio.com/");
var items = $scope.items
$scope.items = [];
var sync = $firebase(ref);
$scope.items = sync.$asArray();
$rootScope.auth = simpleLogin;
return items;
}]);
app.filter('orderObjectBy',['itemsFactory', function (itemsFactory) {
return function (items) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.hot) {
filtered.push(item);
}
};
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (!item.hot) {
filtered.push(item);
}
};
return filtered;
};
}]);
This is the related HTML:
< tr ng-repeat="item in items | orderObjectBy:'hot' track by $index">
Here's what i got in console:
ngRepeat: item in items | orderObjectBy:"hot" track by $index
copeProvider%20%3C-%20%24scope%20%3C-%itemsFactory%20%3C-%orderObjectByFilter at Error (native)
Seems I messed up with dependency injection. But what would be the proper way to do it?
You can take advantage of AngularFire's extensibility to order the list without the need for a directive:
app.factory('HotList', function($firebase) {
function hotComparator(a,b) {
if( a.hot === b.hot ) {
// if both are hot or not, then sort by $id
return strcmp(a.$id, b.$id);
}
else {
// place hot items at the top
return a.hot? -1 : 1;
}
}
function strcmp(str1, str2) {
// http://phpjs.org/functions/strcmp/
return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1));
}
return function(ref) {
var list = $firebase(ref).$asArray();
function resort() {
list.sort(hotComparator);
}
list.$watch(resort);
resort();
return list;
};
});
app.controller('ctrl', function(HotList) {
// automagically sorted by hot/not and $id
$scope.list = HotList(new Firebase(URL));
});
To make your directive work in place, you will want to copy the array and call sort on the copy which will be a great deal simpler.
app.filter('orderObjectBy', function($firebase) {
function hotComparator(a,b) {
if( a.hot === b.hot ) {
// if both are hot or not, then sort by $id
return strcmp(a.$id, b.$id);
}
else {
// place hot items at the top
return a.hot? -1 : 1;
}
}
function strcmp(str1, str2) {
// http://phpjs.org/functions/strcmp/
return ((str1 == str2) ? 0 : ((str1 > str2) ? 1 : -1));
}
return function(items) {
var list = items.slice();
list.sort(hotComparator);
return list;
};
});
And your usage in the view is not quite right, so try it this way:
ng-repeat="item in items track by $id | orderObjectBy:'hot'"

accessing items in firebase

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])

Resources