Backbone: mixing html and javascript in template - backbone.js

In this "hello world" example of a Backbone app http://arturadib.com/hello-backbonejs/docs/5.html, the author renders a template inline like this
render: function(){
$(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
return this; // for chainable calls, like .render().el
},
which, although functional, is a bit of an unmanageable html concatenation.
I've seen authors of other Backbone apps set a template in the view using underscore's template function
template: _.template($('#my-template').html()),
and then render it instead of the html
$(this.el).html(this.template(this.model.toJSON()));
I wanted to try this technique with the hello world app, but when I created the template file, I ran into the problem that it wasn't strictly html. As you'll notice it calls functions
this.model.get('part2')
and the template that I was using as a model (from another author's app, see below) just included html.
Question, What would I need to do to include javascript and html in the same template file so I can make a call to the model?
<script type="text/template" id="item-template">
<div class="company">
<div class="display">
<span class="company-text"></span>
<span class="company-mood">
<span class="mood"></span>
</span>
<span class="company-destroy"></span>
</div>
<div class="edit">
<input class="company-input" type="text" value="" />
</div>
</div>
</script>

See this link Underscore Template for details on what you want to accomplish.
But in general, if you just wanted to interpolate your this.model.get('someAttr'); all you'd need to do is include this in your template.
// Since you call it like this:
$(this.el).html(this.template(this.model.toJSON()));
// Just include this
<div>
<%= someAttr %>
</div>
You're basically passing in the model attributes object and the underscore template just interpolates the properties of that object. You can pass in anything you want although what you do with the render call is what's probably most common.

Related

Ng-show & ng-hide using $rootScope in my project?

I have this code bellow and is working well, I would like to know how can make this variable show in my root-scope?
the problem is I am using now different controllers and directives
so:
if I put this in directive1:
Show
<button ng-click="showme=false">Hide</button>
and this in directive2 does not work:
<div class="wrapper">
<p ng-hide="showme">It will appear here!</p>
<h2 ng-show="showme">This is mah content, yo!</h2>
</div>
full code working if in the same directive html + angular
<div ng-app="">
<h1>Ng-show & ng-hide</h1>
<p class="description">Click on the "show"-link to see the content.</p>
Show
<button ng-click="showme=false">Hide</button>
<div class="wrapper">
<p ng-hide="showme">It will appear here!</p>
<h2 ng-show="showme">This is mah content, yo!</h2>
</div>
</div>
I heard about I can use something like: $rootScope but how I can implement this in that case? thank you.
You need to make sure show is set on the $rootScope. Convenient place for this is run block:
.run(['$rootScope', function($rootScope) {
$rootScope.show = false
}])
After that all scopes will inherit show from its parent.
Another option. You can actually directly refer to $rootScope from any of your template, this is probably simplest solution:
Show
<button ng-click="$root.show = false">Hide</button>

AngularJS - One controller on two sibling DOM elements

I'm trying to do a very simple thing. I'm displaying a list of values with Edit links beside them. Clicking the edit link reveals a form that lets you update the value.
(I've simplified the question so the items just have one field "name". My actual use case has more fields, but is canonically equivalent.)
I've run into something that looks like a bug in Angular, but given my limited experience with it, I'm not so sure. Here's how I'm trying to do it:
<div ng-repeat-start="item in items" ng-controller="ItemCtrl as ctrl" ng-hide="ctrl.isEditing">
<span>Name: {{item.name}}.</span>
<a href='#' ng-click='ctrl.startEditing()'>Edit</a>
</div>
<div ng-repeat-end ng-show="ctrl.isEditing">
<input type='text' ng-model='item.name'/>
<a href='#' ng-click='ctrl.save()'>Save</a>
</div>
My controller looks like this:
app.controller('ItemController', function() {
this.isEditing = false;
this.startEditing = function() { this.isEditing = true; }
this.save = function() { this.isEditing = false; }
});
Clicking on Edit link calls the right controller function, and the first div hides. But the second div does not hide.
When I rearrange the code to look like this (essentially wrapping the two divs with a wrapper element), all is well.
<div ng-repeat="item in items" ng-controller="ItemCtrl as ctrl">
<div ng-hide="ctrl.isEditing">
<span>Name: {{item.name}}.</span>
<a href='#' ng-click='ctrl.startEditing()'>Edit</a>
</div>
<div ng-show="ctrl.isEditing">
<input type='text' ng-model='item.name'/>
<a href='#' ng-click='ctrl.save()'>Save</a>
</div>
</div>
Any idea what is technically wrong with the first version? Note that the <input> boxes do get populated with the right values from item.name.
PS: There's a reason why I'm trying to keep the two divs siblings: in my use case, they are actually implemented as two trs which are supposed to appear right below each other in a table.
It's not a bug from angular but it is quite logical.
<div ng-repeat-start="item in items" ng-controller="ItemCtrl as ctrl" ng-hide="ctrl.isEditing">
<span>Name: {{item.name}}.</span>
<a href='#' ng-click='ctrl.startEditing()'>Edit</a>
</div>
<div ng-repeat-end ng-show="ctrl.isEditing">
<input type='text' ng-model='item.name'/>
<a href='#' ng-click='ctrl.save()'>Save</a>
</div>
If you see the above code you have injected controller only to the first div so obviously sibling div doesn't know what is ctrl or ItemCtrl until and unless you do as in you second way.
So if you want to achieve it as sibling, if you are using routing then add the controller attribute in your route path.
So that the controller will be active for that entire template and you can achieve what you want.
Hope it helps.
Thats because controller has its own scope. When you placed controller ONLY on your first div controllers' scope is limited to only this one div. When you wrapped both your divs inside another and place controller on wrapper, controllers' scope now is all that inside this wrapper. So in this case this works fine and this is not the angular bug

Jasmine-jquery, testing generated GUI for (nested) directives

I recently started using jasmine-jquery (1.3.1) together with angular (1.0.6) and need an advice on testing GUI.
I have some view for controller, which has angular directives, like 'view.html':
<div id='main-div'>
<div my-directive objects-to-iterate='someScopeObjects'>
<span id='default-span'>some default text</span>
</div>
</div>
, and in JS a directive "myDirective" is defined, having template-by-url 'myDirective.html' which includes ng-repeat and makes some nested div (row) foreach in objectsToIterate.
I load fixtures for 'view.html' and 'myDirective.html'.
Now I would like to test that during user interaction there are really some elements (rows) in 'myDirective' repeated block.
Beginning was simple:
var div = $('div#main-div');
div = $compile(div)(scope);
scope.$digest();
expect(div).toBeVisible();
And now I'm stuck. Cannot get access to "generated" source of 'myDirective' element. If I use
div.find('whatever-selector-for-element-my-directive'),
I get
<div my-directive objects-to-iterate='someScopeObjects'>
<span id='default-span'>some default text</span>
</div>
If I try to compile+digest this html against scope, I still get same markup. How could I get "generated" source, looking like (pseudo)
<div id='my-directive-content'>
<div id='object-1'>blah</div>
<div id='object-2'>blah</div>
</div>
in order to check if there are N rows visible to user?
someScopeObjects in scope exist and are valid.
And my next step is actually testing same thing for directives nested inside of 'my-directive', so I somehow have to get access to the scope of 'my-directive'. How? :)
Thank you.

How to write a directive which can render some html code with angular directives, and show it as text?

I think some sample code can explain my purpose.
Some html code with angular:
<div ng-init="buttons=['add','edit','delete']">
<div show-result-as-text>
<button ng-repeat="button in buttons">{{button}}</button>
</div>
</div>
You can see there is a custom directive "show-result-as-text" which I want to define. It should render the inner html code with angular directives, then show them as text.
The final html should be:
<div ng-init="buttons=['add','edit','delete']">
<div show-result-as-text>
<button>add</button>
<button>edit</button>
<button>delete</button>
</div>
</div>
And when the buttons value changes, the escaped html should also be changed.
I've tried to write one myself, but failed after 2 hours of work.
UPDATE
A live demo: http://plnkr.co/edit/fpqeTJefd6ZwVFEbB1cw
The closest thing I could think of is exemplified here: http://jsfiddle.net/bmleite/5tRzM/
Basically it consists in hiding the src element and append a new element that will contain the outerHTML of each src child.
Note: I don't like the solution but it works, so I decided to share it...

Extra divs in itemviews and layouts in Backbone.Marionette

I am trying out Backbone.Marionette and I am confused as to why my Layouts and ItemViews keep generating extra divs.
example is in Coffee btw.
AppLayout = Backbone.Marionette.Layout.extend
template: "#my-layout",
regions:
menu: "#menu",
content: "#content"
MyMenuView = Backbone.Marionette.ItemView.extend
template: '#project_wiz_nav_template'
MyContentView = Backbone.Marionette.ItemView.extend
template: '#project_setup_template'
MyApp = new Backbone.Marionette.Application()
MyApp.addRegions
mainRegion: '#project'
MyApp.addInitializer ->
layout = new AppLayout()
MyApp.mainRegion.show(layout)
layout.menu.show(new MyMenuView())
layout.content.show(new MyContentView())
MyApp.start()
This is what index.html contains:
<div id='project'></div>
<script type='text/template' id='project_wiz_nav_template'> <h2>HI</h2> </script>
<script type='text/template' id='project_setup_template'> <h2>WORLD</h2> </script>
<script id="my-layout" type="text/template">
<h2>Hello!</h2>
<div id="menu"></div>
<div id="content"></div>
</script>
This is what it produces:
<div id="project">
<div>
<h2>Hello!</h2>
<div id="menu">
<div>
<h2>HI</h2>
</div>
</div>
<div id="content">
<div>
<h2>WORLD</h2>
</div>
</div>
</div>
</div>
As you can see, it keeps generating extra divs for the views and the layouts. I've tried adding el: '#menu' and el: '#content' to no avail.
This is not because of Marionette. Backbone generates a <div> class for you by default. You can set the tag via the tagName attribute. See comments on the question for duplicates of this.
A hacky workaround, but jQuery's closest() actually did the job for me. Rather than using the returned myView.el directly, I'm using $(myView.el).closest("div").html() -- as I said, hacky, but as a short-term fix it's working.
I was tinkering with this tutorial: http://davidsulc.com/blog/2013/02/03/tutorial-nested-views-using-backbone-marionettes-compositeview/comment-page-1/#comment-3801, which takes a nested model and creates an accordion view using Bootstrap. I wanted to do the same with his starting point, only using the jQueryUI accordion widget, which is the reason I needed an unwrapped view coming back -- hence the filtering with closest().
Other than adding the jqueryUI links and changing the returned HTML as delineated above, it's working pretty well: http://dartsleague.parentleafarm.com/superheroes/
Specify your el property. I think that will fix it:
http://documentcloud.github.com/backbone/#View-el

Resources