Dojo: loop with data binding - angularjs

I'm just starting with Dojo, and I'm really impressed with the amount and quality of all the modules. Coming from AngularJS however, I find the two-way data binding of Dojo's MVC a bit lacking.
Is there really no way to subscribe to a Dojo Object Store, have a loop in a template to iterate over the items in the store and having the view update automagically when items are added/removed? The example tutorial uses dojo/store/Observable to implement this cumbersome logic:
results.observe(function(item, removedIndex, insertedIndex){
// this will be called any time a item is added, removed, and updated
if(removedIndex > -1){
removeRow(removedIndex);
}
if(insertedIndex > -1){
insertRow(item, insertedIndex);
}
}, true);
function insertRow(item, i){ ... }
function removeRow(i){ ... }
In AngularJS you would do something like this:
<li ng-repeat="item in results">
<span>{{item.text}}</span>
</li>
So do I have to choose between Dojo's extensive widget and modules collection and AngularJS's straight-forward templating with two-way data binding?

First of all, congrats on coming over to the Dojo side. Yes AngularJS is extremely convenient for 2 way data bindings, but you'll soon find out that as an application grows more complex, you'll be needing the help of the powerful (and numerous) Dojo / Dijit / Dojox modules.
You are right dojo/Observable currently provides binding via store in Dojo. It can really achieve the same power as AngularJS. Checkout dgrid examples for a demo.
For convenience, a module has been made for binding in a format similar to Angular JS. Its called dbind. It can be used independently currently and will soon be integrated into Dojo's core. You should also check dojox/mvc/Bind

Related

Need help structuring an Angular app

I have a basic angular app, users can post Adverts, now I am working on how to search / filter for adverts. I am currently using a filter like so..
<a data-ng-repeat="advert in filtered = (adverts | filter:filterBySearch) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit" data-ng-href="#!/adverts/{{advert._id}}" class="list-group-item">
where I have created my own fiter, filterBySearch
I also have a range slider for filtering by a range of prices, and I have all this working with pagination.
My concern is because I have declared <section data-ng-controller="AdvertsController"> at the top of the homepage in order to use the AdvertsController for Advert logic, I am now finding I am putting logic in here around, pagination, the range slider, filtering logic etc. I would like to know how best to split this logic out into their own controllers or whatever it needs.
The controller should not he hadling such complex business logics in itself. It must be used for binding scope elements, handling events, updating states etc. I would suggest pulling your pagination, range slider, filtering logics etc in dedicated angular service and inject the it into your AdvertsController. This way you can also utilize them in any other view/controller you require.
Read more about modularity in AngularJS here
If you have business logic pertaining to elements inside of your tag, then it still makes sense to have all of your code inside of that controller. It might make more sense to rename your Controller to something that better suits your needs.

Polymer-Angular two-way data binding for framework components (core-elements/paper-elements)

I am trying to blend Polymer web components in my Angular application, but I am not being able to get the two-way data binding between these frameworks working. I've already watched this video and already tried the solution provided in this question but it still doesn't work for me. These were my attempts:
Object attribute value
<game-card game="{{game}}" bind-polymer></game-card> - based on post-card.html on the Polymer tutorial. game is an object with id, title, etc.
I created the gameChanged function on the web component and added a new property in the game variable, something like this.game.foo = 'bar';, but if I do
<pre><code>{{game | json}}</code></pre>
right after the component, there's no "foo": "bar" in the stringified object. Even with
publish: {
game: {reflect: true}
},
it doesn't work.
Framework components
<core-input value="{{cool}}" bind-polymer></core-input>
<paper-input value="{{cool}}" bind-polymer></paper-input>
It only works if I edit the element's source code to reflect the value attribute (on core-input.html, as paper-input extends it). I think it isn't a good way of solving this issue.
Am I missing something? Is there a good resource I can look for this Angular-Polymer integration? Searching on Google brings more results about the material than about the library itself and, when found, most of them are "Polymer for Dart" resources.
Try with the NG Polymer Elements lib it solves the 2 way data binding of angular and polymer (core and paper elements) and some other stuff that breaks with angular/polymer, it also has the documentation to addyour own custom polymer elements to the angular binding support
NG Polymer Elements

Angular UI Sortable get index after updated

I really dislike how angular-ui is documented. Sometimes they really don't explain a lot. This is the documentation to sortable-ui: https://github.com/angular-ui/ui-sortable
First, I cannot pass in options.
$scope.sortableOptions = {
cursor:"move"
};
I also changed "move" to "pointer" or "crosshair". Nothing happens.
Second, I need to update the backend by the new order of which the user has sorted. I am not a great javascripter at all (more of a back end developer). The only order-related js function I can find is indexof(). Then it gets very complicated because I need to iterate through all elements and find the new order since the user has rearranged all the elements.
Is there an easier way to get the current order of the list whenever the sortable directive is updated?
I created a demo on plunker (since it allows me to add extra libraries)
http://plnkr.co/edit/uNErHgKL3ohNyFhgFpag?p=preview
Again the cursor part is not working, and I have no idea how to get the order of these items.
I see there are methods on the Sortable UI page...I'm new to angularJS. I just couldn't figure out how to call these methods within AngularJS code.
Seralize method/toArray might not be a good idea..The actual data I'm dealing with does not look like ["one", "two", "three"]. It's more like:
[{"id":"5","article_name":"New Article
Title","article_order":"1","article_author":"Author","article_body":"Start typing your
article here!","is_visible":"1","created_date":"2013-10-27
05:37:38","edit_date":null,"magazineID":"7"},
{"id":"13","article_name":"New Article
Title","article_order":"2","article_author":"Author","article_body":"Start typing your
article here!","is_visible":"1","created_date":"2013-10-27
05:45:10","edit_date":null,"magazineID":"7"}]
If you guys look into this data stream..there is one attribute called article_order. This is the attribute (database column) I am trying to modify...
Read the jQuery UI Sortable docs. There are lots of events you can bind to and methods for serializing the sorted elements. Within the event callbacks you want to use you can make ajax calls to server with updated data
This angular module is simply a wrapper for jQuery UI Sortable.
Create a demo in jsfiddle or plunker that shows the problems you are having
If you use my new sortable Angular.js directive, you would do it like this:
$scope.items = [{"id":"5","article_name":"New Article
Title","article_order":"1","article_author":"Author","article_body":"Start typing
your article here!","is_visible":"1","created_date":"2013-10-27
05:37:38","edit_date":null,"magazineID":"7"},
{"id":"13","article_name":"New Article
Title","article_order":"2","article_author":"Author","article_body":"Start typing
your article here!","is_visible":"1","created_date":"2013-10-27
05:45:10","edit_date":null,"magazineID":"7"}];
$scope.onChange(fromIdx, toIdx) {
$scope.items[fromIdx].article_order = toIdx;
$scope.items[toIdx].article_order = fromIdx;
// OR
// var temp = $scope.items[fromIdx].article_order;
// $scope.items[fromIdx].article_order = $scope.items[toIdx].article_order;
// $scope.items[toIdx].article_order = temp;
}
HTML:
<ul ng-sortable="items"
ng-sortable-on-change="onChange">
<li ng-repeat="item in items" class="sortable-element" ng-style="{backgroundColor: item.color}">
{{item.name}}, {{item.profession}}
</li>
</ul>
See demo + documentation here:
https://github.com/schartier/angular-sortable
https://github.com/schartier/angular-sortable-demo
I guess I got into an issue similar to you. If we subscribe the update callback we don't get the latest order of items. But using the stop event handler helped me. While using angular ui sortable, we get the model updated with the latest order in the stop event handler. You can post this data to backend or wherever you want to store..Hope this helps...:)
You can refer the jquery ui sortable documentation for stop here
http://api.jqueryui.com/sortable/#event-stop

Using Backbone models with AngularJS

Recently I was thinking about the differences and similarities between Backbone.js and AngularJS.
What I find really convenient in Backbone are the Backbone-Models and the Backbone-Collections. You just have to set the urlRoot and then the communication with the backend-server via Ajax basically works.
Shouldn't it be possible to use just the Backbone-Models and Collections in AngularJS application?
So we would have the best of both worlds two-way data-binding with AngularJS and convenient access to the server-side (or other storage options) through Backbone-Models and Collections.
A quick internet search didn't turn up any site suggesting this usage scenario.
All resources either talk about using either the one or the other framework.
Does someone have experience with using Backbone-Models or Collections with AngularJS.
Wouldn't they complement each other nicely? Am I something missing?
a working binding for example above...
http://jsbin.com/ivumuz/2/edit
it demonstrates a way for working around Backbone Models with AngularJS.
but setters/getters connection would be better.
Had a similar idea in mind and came up with this idea:
Add just a getter and setter for ever model attribute.
Backbone.ngModel = Backbone.Model.extend({
initialize: function (opt) {
_.each(opt, function (value, key) {
Object.defineProperty(this, key, {
get: function () {
return this.get(key)
},
set: function (value) {
this.set(key, value);
},
enumerable: true,
configurable: true
});
}, this);
}
});
See the fiddle: http://jsfiddle.net/HszLj/
I was wondering if anyone had done this too. In my most recent / first angular app, I found Angular to be pretty lacking in models and collections (unless I am missing something of course!). Sure you can pull data from the server using $http or $resource, but what if you want to add custom methods/properties to your models or collections. For example, say you have a collections of cars, and you want to calculate the total cost. Something like this:
With a Backbone Collection, this would be pretty easy to implement:
carCollection.getTotalCost()
But in Angular, you'd probably have to wrap your custom method in a service and pass your collection to it, like this:
carCollectionService.getTotalCost(carCollection)
I like the Backbone approach because it reads cleaner in my opinion. Getting the 2 way data binding is tricky though. Check out this JSBin example.
http://jsbin.com/ovowav/1/edit
When you edit the numbers, collection.totalCost wont update because the car.cost properties are not getting set via model.set().
Instead, I basically used my own constructors/"classes" for models and collections, copied a subset of Backbone's API from Backbone.Model and Backbone.Collection, and modified my custom constructors/classes so that it would work with Angular's data binding.
Try taking a look at restangular.
I have not implemented it anywhere, but I saw a talk on it a few days ago. It seems to solve the same problem in an angular way.
Video: http://www.youtube.com/watch?v=eGrpnt2VQ3s
Valid question for sure.
Lot of limitations with the current implementation of $resource, which among others doesn't have internal collection management like Backbone.Collection. Having written my own collection/resource management layer in angular (using $http, not $resource), I'm now seeing if I can substitute much of the boilerplate internals for backbone collections and models.
So far the fetching and adding part is flawless and saves code, but the binding those backbone models (or the attributes within, rather) to ng-models on inputs for editing is not yet working.
#ericclemmons (github) has done the same thing and got the two to marry well - I'll ask him, get my test working, and post the conclusion...
I was wondering the same-
This is the use-case:
salesforce mobile sdk (hybrid) has a feature called smartstore/smartsync, that expects backbone models/collection ,which gets saved to local storage for offline access .
And you guessed it right, we want to use angularjs for rest of the hybrid app.
Valid question.
-Sree
You should look at the angularJS boilerplate with parse here. Parse is backbone like, but not exactly backbone. Thats where im starting my idea of a angularJS backboneJS project

Backbone Marionette modules as Widgets similar to Twitter Flight

I'm reading up in choosing the correct client-side framework to segment/modularize my frontend code in Widgets.
Basically what I have/want is:
a complex website with multiple pagetypes, so no single-page application.
all pages are able to render a complete page WITHOUT the use of javascript. IOW: javascript is used as enrichment only.
Lots of pages have a very dynamic way in which widgets can be shown on screen. To overcome complexity at the server-side I've modularized my code into widgets (composite pattern), where each widget is responsible for it's own:
server-side controller code
server-side templating (using hogan/mustache)
routing endpoints, should it need to be called from the client
structural css (css converning the structure of the widget as opposed to the look&feel)
a server-side RegionManager ultimately decides which widgets are rendered and where they are rendered on screen. Endresults is that the RegionManager spits out the entire html (server-generated) as the composite of the rendering of all of it's widgets.
Now, some of these widgets DO have client-side logic and need rerendering on the client. Take a searchpage for instance, which needs to be able to update through ajax. (I've described this process, which uses DRY templating on client and server, here)
What I ultimately want is that, given I already use the composite pattern on the server, to extend this to the client somehow so that a Widget (1 particular logic block on the screen) contains all mentioned server-side code, plus all needed client-side code.
I hope this makes sense.
Would Marionette be suited to be used as a client side framework in this scenario? I'm asking since I'm not 100% sure if the concept of a Marionette Module is what I describe as being a Widget in above scenario. (I'm mentioning Twitter Flight in my question, since I believe this would be a fit, but it currently is so new that I'm hesitant to go with it at the moment_
I think basically what I'm asking is if anybody has some experience doing something along these lines.
I think just using Backbone.js is perfect for this type of application you are describing. You have probably already read this, but most of the backbone literature is focused around your views having associated server generated JSON models and collections, then using the View's render function to generate (on the client) the HTML UI that represents the model/collection.
However it doesn't have to be used this way. In fact there is nothing stopping you attaching views to existing elements that contain content already, which gives you all of the benefits of Backbone's modularity, events system and so on. I often use views that have no model or collection, purely because I like the conformity of style. I have also used an approach like I describe below in the cases where I have had to work with older, existing applications that have not yet got, or never will have a nice REST API, but they do provide content in HTML.
Firstly, lets assume the following HTML represents one of your widgets:
<div id="widget">
<div class="widget-title"></div>
<div class="widget-body">
<!-- assume lots more html is in here -->
Do something!
</div>
</div>
In this case, you could use backbone with a single Widget Model. This would be a very simple model, like this:
App.WidgetModel = Backbone.Model.extend({
intialize: function () {
this.url = this.options.url;
}
});
Take note of the fact the Widget receives a URL as a parameter to its constructor/initialize function. This widget model would represent many of your widgets (and of course you could adopt this general approach with more complicated models and pluck different data from the rendered HTML). So next for your views. As you probably know, normally you pass most views a model or collection when you instantiate them. However in this case, you could create the Widget model in your View's initialize Function and pass it a URL from the pre-rendered HTML as follows:
App.WidgetView = App.View.ComboboxView = Backbone.View.extend({
initialize: function () {
this.model = new App.WidgetModel({}, { url: this.$("a").attr("href") });
}
// rest of the view code
});
So instantiating the view would be something like:
new App.WidgetView({el: $("#widget")})'
By doing all of the above you can do pretty much everything else that backbone offers you and its modular and encapsulated nicely, which is what you are after.
The end result of this whole approach is:
You have rendered the Widget UI as pure HTML which (I assume) is functional without JavaScript.
You attach a View to the existing HTML.
You pass into the View as options, content by extracted (such as a URL) from the rendered HTML with jQuery.
The View is responsible for instantiating the Model passing on the relevant options the model needs (such as a URL).
This means all dynamic server side content is intially contained in the rendered HTML and your View is a modular JavaScript component that can do stuff to it, which I think is the end result you're after.
So you mentioned that you would like to have AJAX functionality for your widgets and that fine with this approach too. Using this approach, you can now use the standard Backbone fetch and save functions on the Widget model to get new content. In this example it is from the URL retrieved from the rendered HTML. When you get the response, you can use the view's, render function, or other finer grained functions to update the HTML on the page as required.
A few points:
The only thing to look out for is that you'll need to change the content type of the fetch and save functions to "text/html" if that's what the server is providing. For example:
this.model.fetch({
type: "POST",
contentType: "text/html"
});
Lastly, the model I have proposed is instantiated with no content. However if your ajax calls are a content type of "text/html", you may need to play around with you model so it can store this content in its attributes collection properly. See this answer for more information.

Resources