Am getting this error performing this query with firebase, well not error but it not returning anything.
This is the factory
.factory("items", function($firebaseArray) {
var itemsRef = new Firebase("https//*****.firebaseio.com/comments");
return $firebaseArray(itemsRef);
})
and in my controller this is how am calling .using the orderby property/attribute
.controller('tdCtrl', function($scope, FeedList, $firebaseArray, $firebase,
$stateParams, dataStore, feedSources, $ionicModal, items) {
$scope.items=items //working when am calling normally
but now i want get all the comment with the hashkey 3432 -- which is dynamic but used as 3432 for easier explanation
$scope.items = items.orderByChild("hashKey").equalTo(3434).on("child_added",
function(snapshot) {
});
this is the post function
.........
$scope.comment.hashkey=3432;
$scope.items.$add(comment);
.............
Solved - guess read all docs before attempting anything with firebase , alot of deprecated code used by most blog tutorial , so docs first :)
var fireRef= new Firebase("https//****.firebaseio.com/comments");
$scope.items = $firebaseArray(fireRef.orderByChild("hashKey").equalTo(id).limitToLast(10));
Related
I am trying to create a multiple input tags-input field in AngularJS, where I also want to add auto complete, so that on typing atleast 3 letters in the input field, the already existing tag names in the database appear as suggestions in the dropdown.
Here is the problem:
I am using Routing.generate() module of the FOSjsRouting Bundle to call the controller action inside the javascript code (the action in-turn returns the following JsonResponse object):
Here is the controller code:
/**
* #Route("/jsondata", options={"expose"=true}, name="my_route_to_json_data")
*/
public function tagsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT t.text
FROM AppBundle:Tag t
WHERE t.id > :id
ORDER BY t.id ASC'
)->setParameter('id', '0');
$tagsdata = $query->getScalarResult();
$response = new Response(json_encode($tagsdata));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Here is the AngularJS code:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get(Routing.generate('my_route_to_json_data'));
};
});
Here is the result I get:
Now when I save the Json response in tags.json and call it without using Routing.generate() module:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get('http://localhost/AngularTags/web/js/tags.json');
}
});
I get the perfectly working result:
Now I know the problem lies with proper usage of Routing.generate(). Since I am new to AngularJS and am just learning how to debug in console(which m loving by the way), m not entirely sure if I can figure out the problem on my own. Any help is appreciated.
n m sorry the post became too long, just wanted to make it clear.
So, awaiting response...
This is not a problem with AngularJS, this is a problem of variable scope in JavaScript.
Did you import the scripts in your HTML as specified in the documentation?
I have recently posted a similar question, but this is not a duplicate.
Apologies for the code heavy post but I wanted to provide as much context as possible. I am having an issue with defining the analytics tool, 'Amplitude' as a service in my Angular.js application. Services are supposed to act as singletons throughout an application (source), so I am confused to be getting the following behavior.
In my app.js file, I call AmplitudeService.logEvent('EVENT_NAME') in a .run function which successfully logs the event to Amplitude. Note: Console.log(AmplitudeService) returns an object with all the correct functions here.
However, when I call AmplitudeService.logEvent('EVENT_NAME') within any other controller, such as header.js I do not ever see any data in my Amplitude dashboard. Note: Console.log(AmplitudeService) returns an identical object within header.js to the one returned from app.js
Would appreciate any and all insight!
P.S. The official AmplitudeJS SDK is here. I am trying to implement it through this wrapper.
AmplitudeService.js (source)
Note: If you check the author's syntax, he returns an object at the end of his service. In my research, I've read to use the "this" keyword when defining Service functions (source), and that you don't need to return an object as you would with a Factory, so I have updated it accordingly.
angular.module('AmplitudeService', [])
.service('AmplitudeService',
['$amplitude', '$rootScope', 'amplitudeApiKey', '$location',
function ($amplitude, $rootScope, amplitudeApiKey, $location) {
this.init = function() {
$amplitude.init(amplitudeApiKey, null);
}
this.identifyUser = function(userId, userProperties) {
$amplitude.setUserId(userId);
$amplitude.setUserProperties(userProperties);
}
this.logEvent = function(eventName, params) {
$amplitude.logEvent(eventName, params);
}
}]);
angular-amplitude.js (source)
This allows access to "$amplitude" throughout the application
(function(){
var module = angular.module('angular-amplitude', ['ng']);
module.provider('$amplitude', [function $amplitudeProvider() {
this.$get = ['$window', function($window) {
(function(e,t){
var r = e.amplitude || {};
var n = t.createElement("script");
n.type = "text/javascript";
n.async = true;
n.src = "https://d24n15hnbwhuhn.buttfront.net/libs/amplitude-2.2.0-min.gz.js";
var s = t.getElementsByTagName("script")[0];
s.parentNode.insertBefore(n,s);
r._q = [];
function a(e){
r[e] = function(){
r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));
}
}
var i = ["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];
for(var o = 0; o < i.length; o++){
a(i[o])
}
e.amplitude = r
}
)(window,document);
return $window.amplitude;
}];
}]);
return module;
}());
App.js
angular.module('app', [
'ngRoute',
'angular-amplitude',
'AmplitudeService',
])
.run(['AmplitudeService', function(AmplitudeService){
console.log(AmplitudeService); // Outputs 'Object {}'
AmplitudeService.init();
*AmplitudeService.logEvent('LAUNCHED_SITE'); // This logs the event*
console.log(AmplitudeService); // Outputs 'Object {}'
}])
Header.js
angular.module('app.common.header', [])
.controller('HeaderCtrl', [ '$rootScope', '$scope', '$location','$route', '$window', 'AmplitudeService', function($rootScope, $scope, $location, $route, $window, AmplitudeService){
$scope.goToSearch = function(term) {
$location.path('/search/' + term);
console.log(AmplitudeService); // Outputs 'Object {}'
*AmplitudeService.logEvent('SEARCHED');* // This does not log the event
};
}]);
Update: I have tried switching the Service to a Factory and that did not generate any new results.
Found the solution and hope this is helpful to anyone that comes across this. My solution was to initialize the SDK by calling AmplitudeService.init() within a .run() function within app.js, which initialized an amplitude object within my window. From there forward, I included $window as a service in each of my controllers and called $window.amplitude.logEvent('event_name_here');
Feel free to contact if you have questions. Thanks.
We had similar issues on a large project and we created a wrapper providing a directive to init Amplitude and a service to provide the logEvent and sendUserId.
I am working on displaying collection that I got from DB in angular with firebase DB. I have those controller and service setup. in the html, I use search.users expecting it will hold all the data that I got from the DB but it won't show up. I can't figure out why. I tried few things like angular.copy or $broadcast with no luck. Can anyone help advise on this? Appreciated in advance.
.controller('SearchController', function ($scope, SearchService, logout, $location){
var search = this;
search.users = SearchService.users;
//$scope.$on('evtputUsers', function () {
// search.users = SearchService.users;
//});
})
//service for SearchService
.factory('SearchService', function ($http, $rootScope){
var userRef = new Firebase("app url");
var broadcastUsers = function () {
$rootScope.$broadcast('evtputUsers');
};
//get the user info
//insert the data to the db.
//retrieving the data
var dbUsers;
userRef.child('users').on('value', function(snapshot){
dbUsers = snapshot.val();
// angular.copy(snapshot.val(), dbUsers);
console.log('usersinDB:',dbUsers);
broadcastUsers();
}, function(err){
console.error('an error occured>>>', err);
});
return {
users: dbUsers
};
})
Rather than using $broadcast() and $on() you should use the AngularFire module.
AngularFire provides you with a set of bindings to synchronizing data in Angular.
angular.module('app', ['firebase']) // 1
.controller('SearchCtrl', SearchCtrl);
function SearchCtrl($scope, $firebaseArray) {
var userRef = new Firebase("app url")
$scope.users = $firebaseArray(userRef); // 2
console.log($scope.users.length); // 3
}
There are three important things to take note of:
You need to include AngularFire as firebase in the dependency array.
The $firebaseArray() function will automagically synchronize your user ref data into an array. When the array is updated remotely it will trigger the $digest() loop for you and keep the page refreshed.
This array is asynchronous. It won't log anything until data has populated it. So if you're logs don't show anything initially, this is because the data is still downloading over the network.
I'm currently learning AngularJS and similar stuff, and today I've encountered a problem (probably with async).
What I'm trying to do, is to use an Angular factory to get some data from Firebase and then use the data in a controller.
App.factory('Jobs', ['$firebaseObject', function($firebaseObject) {
var ref = new Firebase('https://myapp.firebaseio.com/Jobs');
return $firebaseObject(ref);
}]);
App.controller('JobsController', ['$scope', 'Jobs', function($scope, Jobs) {
Jobs.$bindTo($scope, 'allJobs');
console.log($scope.allJobs);
}]);
This is working pretty OK. When I put {{ allJobs | json }} in a template- it is updated after few seconds. The problem is that in the controller $scope.allJobs is returning undefined (probably because the response from Firebase arrived later than the code has been executed.
My question is, how to write it, so I can access $scope.allJobs directly in the controller?
You could do something like this:
App.factory('Jobs', ["$firebaseObject",
function($firebaseObject) {
// create a reference to the Firebase where we will store our data
return function(url){
var ref = new Firebase(url);
// this uses AngularFire to create the synchronized array
return $firebaseObject(ref);
};
}
]);
Then in your controller:
App.controller('JobsController', ['$scope', 'Jobs', function($scope, Jobs) {
$scope.allJobs = Jobs('https://myapp.firebaseio.com/Jobs');
$scope.allJobs.$loaded().then();
}]);
This is showing the $loaded method as opposed to $bindTo. As the other answers/comments mention, $bindTo may be the better way to go.
Referencing to this Firebase documentation: https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject-bindtoscope-varname
I can just do it very very simple:
App.controller('JobsController', ['$scope', 'Jobs', function($scope, Jobs) {
Jobs.$bindTo($scope, 'allJobs').then(function() {
// now I have access to $scope.allJobs when everything is downloaded from Firebase
});
}]);
Using this service to perform promises:
using this service to perform promises: Improving AngularJS Simple Factory - wrapper around PhoneGap Storage API
I can't figure out, why i am getting error when using ng-model directive and promises.
TypeError: Cannot assign to read only property 'favourite'
when clicking
<div ng-controller="DishCtrl">
<input type="checkbox" name="favourite" ng-model="dish.favourite" required smart-float ng-click="markFavourite(dish)"/>
</div>
and controller as follows:
angular.module('App')
.controller('DishCtrl', function($scope, NotificationService, MediaService, SQLService, $routeParams, $rootScope) {
var dishId = $routeParams.dishId;
SQLService.getDish(dishId).then(function(results) {
$scope.dish= results;
});
if i remove ng-model directive everything works. So promise is resolved correctly i quess.
I also tried to bind model directly - without promise and works.
Is it a bug, or did i missed something?
I am trying also resolving promises as example in here: http://jsfiddle.net/8HjgJ/
Did you try to initialize your scope variable before the promise is resolved. Something like that :
angular.module('App')
.controller('DishCtrl', function($scope, NotificationService, MediaService, SQLService, $routeParams, $rootScope) {
$scope.dish = false; //Default value, will be updated when promisse is resolved
var dishId = $routeParams.dishId;
SQLService.getDish(dishId).then(function(results) {
$scope.dish= results;
});
i dont understand why, but copying the object in Service:
Improving AngularJS Simple Factory - wrapper around PhoneGap Storage API
before resolving the promise helps!
function querySelectSuccess(tx, results) {
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
console.log('ts',results.rows.item(i));
var temp_copy = angular.copy(results.rows.item(i));
output_results.push(temp_copy);
}
deferred.resolve(output_results);
}