AngularFire ObjectFactory Childobjects cause Circular Dependency - angularjs

Using AngularFire, I am extending the object factories in order to have encapsulated data and to allow specific features, as explained in the official tutorial. I have a data structure like the following:
{
'articles': {
'article-asd876a': {
title: 'abc',
text: 'lorem ipsum ...',
comments: {
'comment-ad4e6a': true,
'comment-dsd9a7': true
}
}
},
'comments': {
'comment-ad4e6a': {
text: 'comment text1',
articleId: 'article-asd876a'
},
'comment-dsd9a7': {
text: 'comment text2',
articleId: 'article-asd876a'
}
}
}
Now I would love to be able to do this:
var article = new Article(8); // Returns the object created by my object factory, fetching data from firebase
var comments = article.getComments(); // Returns an array of type Comment
var firstText = comments[0].getText();
var article2 = comments[0].getArticle(); // article2 === article
But this fails for me on many levels. One of them being: In Article, I can only store the Comment ID, and therefore have to recreate the Comment Object using new Comment(commentId), for which I need to inject Comment into Article. The same is true for Comment, so that I end up with a circular dependency Article -> Comment -> Article. The following fiddle shows the behavior: http://jsfiddle.net/michaschwab/v0qzdgtq/.
What am I doing wrong? Is this a bad concept/structure for angular? Thanks!!

What am I doing wrong? Is this a bad concept/structure for angular?
Thanks!!
You are creating circular dependencies.
I can do var Comment = $injector.get('Comment'); to avoid the error,
is that the best solution?
I see two solutions:-
1) Lazy injecting solution (you suggested yourself)
This is the best solution to avoid those circular dependencies in AngularJS. Although looking at the AngularFire documentation you are into an uncharted territory as some of these things in AngularFire are experimental in nature.
Here is the working fiddle from your
var Comment = $injector.get('Comment');
You are essentially lazy injecting your references.
http://jsfiddle.net/yogeshgadge/ymxkt6up/5/
2) Module Run block:
With this option you may be able to inject those dependencies into your factories instead of using $injector.

Related

Multiple filters on a collection with angular-meteor

I'm following the Meteor To-Do App tutorial with Angular integration and am learning about filtering collections. I've been able to implement a simple filter on a collection for the app I'm working on by following the principles in the tutorial, but now I'm stuck trying to figure out how to add multiple queries to the filter.
In the example, you can view incomplete tasks by toggling a checkbox. This is implemented in the controller by watching $scope.hideCompleted for changes and passing it as a Mongo query to filter the Meteor collection.
Watcher
$scope.$watch('hideCompleted', function() {
if ($scope.hideCompleted)
$scope.query = {checked: {$ne: true}};
else
$scope.query = {};
});
Collection filter
$scope.tasks = $meteor.collection(function() {
return Tasks.find($scope.getReactively('query'), {sort: {createdAt: -1}})
});
How do I make the query support multiple filters? For example, say I've chosen to extend the example and have ranked each to-do item by priority. I then would have an an input field for the user to filter the collection by priority, whose value is bound to $scope.priority. Now, if I wanted to filter the to-do list by incomplete and priority=$scope.priority tasks, I understand the Mongo query would need to be something along the lines of Tasks.find({ $and: [{ checked: {$ne: true} },{ priority: $scope.priority }]},{ sort: { createdAt: -1 } }).
In my app, I've been able to make two watchers properly track changes to two scope variables, analogous to my example with $scope.hideCompleted and $scope.priority, but I don't know how to take the next step to merge the queries when filtering the collection. I've also tinkered around a little with this package, since I'll eventually hope to be able to filter and sort by many criteria, but I didn't get too far with it before switching to the concepts I've described here.
I'd appreciate any help with this. Thank you!
This would be my approach:
$meteor.autorun($scope, function() {
// uncomment subscribe after you've got to that point
// $scope.$meteorSubscribe('yourSubscription').then(function() {
$scope.tasks = $scope.$meteorCollection(function() {
return Tasks.find({
checked: $scope.getReactively('model.hideCompleted'),
priority: $scope.getReactively('model.priority')
}, { sort: { createdAt: -1 } });
});
// });
});
A couple of things here:
Once you have removed autopublish you can uncomment the $scope.$meteorSubscribe method and replace "yourSubscription" with the name of your actual subscription.
$meteor.autorun will fire every time any getReactively variable changes.
$scope.$meteorSubscribe and $scope.$meteorCollection are favored as they will remove the subscriptions and object/collection when the scope is destroyed.
If you have any issues then perhaps I can setup a demo for you to look at.
Well, I guess I was a lot closer than I had expected, so I'll answer my question and share what I did to implement multiple filters with regards to the hypothetical extension of the to-do app.
I made hideCompleted and priority scope variables into properties of a scope object model, and used a single watcher with the argument true at the end to check for object equality (for any changes to model or its properties). I then generated $scope.query by stitching together "sub-queries." I've added the code below.
This seems to be working fine for now, but I'm not sure if it's the best solution, so I will continue experimenting, and I will update my answer if I find anything better. I'd be interested in any other approaches, though!
Watcher
var initQuery=true;
var subQueries=[];
$scope.$watch('model', function() {
if (!initQuery){
subQueries=[];
if ($scope.model.hideCompleted)
subQueries.push({checked: {$ne: true}});
if ($scope.model.priority)
subQueries.push({priority: $scope.model.priority});
$scope.query = { $and: subQueries};
} else {
initQuery = false;
$scope.query = {};
}
}, true);
Filter Collections (unchanged)
$scope.tasks = $meteor.collection(function() {
return Tasks.find($scope.getReactively('query'), {sort: {createdAt: -1}})
});

How to prepare arrays for insertion into Firebase database?

I have a question about adding arrays to Firebase using AngularFire. Let's start with a quick example. What I tend to do when my users on the front end create a list is something like this:
angular.module("app", ["firebase"])
.controller("createListCtrl", function($scope, $firebaseArray) {
console.log("controller loaded");
$scope.newList = [];
$scope.addItemToList = function(itemlist) {
console.log(itemlist);
$scope.newList.push({
"item": itemlist,
"done": false
});
}
$scope.sendToDb = function() {
var ref = new Firebase("https://xxxxxx.firebaseio.com");
var list = $firebaseArray(ref);
list.$add({
"list": $scope.newList
}).then(function(ref) {
var id = ref.key();
console.log("added record with id " + id);
console.log(list.$indexFor(id)); // returns location in the array
})
}
Ok all nice and dandy and it all works great but I then I read this article:
https://www.firebase.com/blog/2014-04-28-best-practices-arrays-in-firebase.html
And I heard more people say to avoid arrays and I see the problem with array in Firebase, but what is the alternative, the article says this structure:
{foo: {counter: 1}, bar: {counter: 1}, baz: {counter: 1}};
Is that really a better structure? I think it gets messy and I don't even know how I would achieve this structure starting with something like this:$scope.newList = {};. Is it really a problem doing it with an array. Are arrays really evil in Firebase? Thanks in advance for an explanation or a better alternative.
edit
This is how the list is stored in Firebase, which does not seem very good:
---uniqueID
---list
---0
---done:false
---item:"item1"
---1
---done:false
---item:"item2"
---2
---done:false
---item:"item3"
The $firebaseArray class, which you're already using, provides a mapping between Firebase's ordered collections (which use push ids for their keys) and AngularJS's array (which use regular arrays).
So in your controller's constructor instead of creating a local array for itemList, create a two-way synchronized $firebaseArray:
$scope.newList = $firebaseArray(new Firebase("https://xxxxxx.firebaseio.com"));
The blog post you're referring to served as the basis for quite a few changes to AngularFire since then. I highly recommend that you work through the AngularFire development guide. It will take at most a few hours and will answer many more questions than just this one (which is covered in the section on synchronized arrays).
Update
Thanks for the update. I now get what you're trying to do. So you initially want to keep the list of items client-side only, and then all at once save it to Firebase.
In that case, I'd write sendToDb like this:
$scope.sendToDb = function () {
var ref = new Firebase("https://xxxxxx.firebaseio.com");
var listRef = ref.push();
$scope.newList.forEach(function(item) {
var itemRef = listRef.push({ item: item.item, done: item.done });
console.log('Added item with key: '+itemRef.key());
});
}
This uses the regular Firebase JavaScript SDK. But since AngularFire is built on top of that, they will co-exist without problems.
So instead of pushing the array in one go, I simply loop over the items in it and push each of them.
Working fiddle here: https://jsfiddle.net/frankvanpuffelen/vnh5dbwq/11/

How to define hidden properties on Angular $scope

Consider:
$scope.taylor = {
firstName: 'taylor',
lastName: 'mcintyre',
order: 22
}
Using $resource, I might want to save this:
people.save($scope.taylor);
However, I do not want the property "order" to be sent along with the request.
Angular ignores properties prefixed with '$$' for it's own internal use, but it doesn't feel right prefixing my own hidden properties in this way, e.g.
$scope.taylor = {
firstName: 'taylor',
lastName: 'mcintyre',
$$order: 22
}
Deleting unwanted properties is the common-sense solution, but does Angular have a better solution for this?
I know you are looking for an "Angular way" to exclude keys, but angular.copy() doesn't seem to support this. The angular.toJson() documentation states: Properties with leading $ characters will be stripped since angular uses this notation internally. This sounds like using $ should be reserved for angular and not used by us in our objects.
In light of the situation I created a simple CodePen example showing how easily this can be done using a library like UnderscoreJS.
I'm sure there are more elegant ways to do this, but my example does accomplish what I understood to be your primary goal.
I included the UnderscoreJS library in my file and added the following code:
var person = {
firstName: 'John',
lastName: 'Smith',
order: 22,
excludeKeys: [
'order',
'excludeKeys'
]
};
var personCopy = _.omit(person, person.excludeKeys);
console.log('person: ', person);
console.log('person copy: ', personCopy);
I hope this is useful.

Firebase.push failed: first argument contains an invalid key ($$hashKey)

I recently started learning AngularJS+Firebase. I'm trying to write in my firebase an object like this:
{
title: "Personal Information",
say: [
[{ "eng": "What's", "ukr": "Що є" }, { "eng": "your", "ukr": "твоє" }, { "eng": "surname?", "ukr": "прізвище?" }],
[{ "eng": "Smith", "ukr": "Сміт" }],
[{ "eng": "What's", "ukr": "Що є" }, { "eng": "your", "ukr": "твоє" }, { "eng": "first", "ukr": "перше" }, { "eng": "name?", "ukr": "ім'я?(не фамілія)" }]
]
}
with line:
lessondata.add($scope.topic);
where 'lessondata' is service created with angularFireCollection() and $scope.topic - object bound to my UI.
But got the following error:
Firebase.push failed: first argument contains an invalid key ($$hashKey) in property 'say.0.0'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"
As I understood Firebase do not allow to use 0 as a key even if it's a key in an attached array for which zero key is natural. So should I change my object structure in some hardcoded instance or I miss something? Thanks in advance!
EDIT: As Anant points out in the comments, in the latest stable version of Angular (1.0.7 atm), you can use angular.copy(obj) to remove $$hashkey attributes.
Like Michael said, the '$' in '$$hashKey' is the issue. Angular creates the $$hashKey properties behind the scenes (see more here: https://groups.google.com/forum/#!topic/angular/pI0IgNHKjxw). I've gotten around this issue by doing something like myRef.push(angular.fromJson(angular.toJson(myAngularObject))).
The issue is the $ in "$$hashKey", not the 0. 0 is allowed.
I wanted to throw another answer in here that is much simpler, just use track by in your repeat. It will get rid of the $$hashKey attribute that is causing so much grief.
<div ng-repeat="item in items track by $index">{{item.name}}</div>
I'm a bit late to this but I thought I would like to add my two cents as I was shaking my head to all the other answers. Hopefully this can help you to avoid this issue all together.
Use the angularFire library intended to handle angular data and use it's methods.
while yes you can use the pure javascript library methods to .push() .add() .update(), .set() ect.
So if you want to avoid any clashes when firebase communicates with angular javascript you need to be using the appropriate .$foo() methods (i.e. .$save()). In your case just add the $ to your .add() (make it .$add())
so use lessondata.$add($scope.topic);
differences when saving with firebase's vs angularfire's
AngularFire's $save() method is implemented using Firebase's set() method.
Firebase's push() operation corresponds to AngularFire's $add() method
Typically you should be using set()/$save() if you either have an object that already exists in the database or if you are working with objects that have a natural key.
more info on that here: https://stackoverflow.com/a/35959496/4642530
Things to note with AngularFire
For a callback:
and if you want a callback to know if your data saved correctly you can do something like this:
var list = $firebaseArray(ref);
list.$add({ foo: "bar" }).then(function(ref) {
var id = ref.key();
console.log("added record with id " + id);
list.$indexFor(id); // returns location in the array
});
I was surprised this wasn't mentioned earlier in any of the other answers, but take a look at these docs https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray-addnewdata
Cheers.
The best way to get rid of the $$hasKeys is to use "track by" in ng-repeats as in the following (as mentioned in the answer above)
<div ng-repeat="(key, value) in myObj track by $index"> ... </div>
but you can also set track as par of ng-model-options
ng-model-options="{ trackBy: '$value.someKeyOnYourObject' }"
on a form control. This way also improves performance of your angular app.
Another way is to remove the $$hashKey is using
angular.copy(someObj);
If all else fails, you could also use lodash to remove the keys that start with the "$".
_.omitBy(yourObject, function(value, key){return _.startsWith(key, '$');});
You can also strip out the property before pushing it.
delete $scope.topic.$$hashKey

Multiple resources in one view

I want to display a list of images and their respective comments. Like:
Image url | Format | Comments
http://example.com/img.jpg | 1280x420 | [Comment 1], [Comment 2] ...show all ...show all
http://example.com/img2.jpg | 630x590 | [Comment 1], [Comment 2] ...show all
I have two resouces: /images and /comments/{image_id}
What is the recommended way to fetch the comments for each image to be able to display them on the same row? Does Marionette have a helper for this?
In my opinion, these look like a good place to use relational models. Backbone doesn't support these out of the box, so you'll need a plugin. Have a look at Backbone-Relational or supermodel.js. These projects provide better forms of model nesting than the default implementation. From there, use nested composite views to render the collections.
From what I know Marionette does not have such helper. I think you can use something simple like:
var ImageComments = Backbone.Collection.extend({
initialize: function(models, options) {
options || (options = {});
this.imageId = options.imageId;
Backbone.Collection.prototype.initialize.apply(this, arguments);
},
urlRoot: function() {
return 'comments/' + this.imageId;
}
});
var id = 1,
image = new Image({ id: id }),
comments = new ImageComments(null, { imageId: id });
$.when(image.fetch(), comments.fetch()).done(function() {
// .. do your things with image & comments
});
This describes simple case, if that's commonly used in your application you might want to implement your own fetch method (e.g. for image, that will also fetch comments) or use plugins like Backbone-relational or Backbone-associations
You can use nested composite views.
http://davidsulc.com/blog/2013/02/03/tutorial-nested-views-using-backbone-marionettes-compositeview/
You can also do old fashioned in template loops for the comments
http://www.headspring.com/an-underscore-templates-primer/

Resources