Backbone & Underscore: unable to pass model to template for evaluation - backbone.js

I'm having trouble with passing model data from a Backbone View to a template in Underscore. I want to pass an array into the template so I can evaluate using _.each.
My code is below:
templateSettings
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\{([\s\S]+?)\}\}/g
};
Interpolate is {{ }} and evaluate is {[ ]}. Unless my regex is incorrect
View
el: $('#assasinationBackbone'),
events: {
'click #newHitJob': 'addNewHitJob'
},
initialize: function() {
},
addNewHitJob: function() {
var hitMen = new HitManList();
var template = _.template($('#newHitJobTemplate').html());
hitMen.fetch({
success: function() {
$('#newHitJobForm').html(template(hitMen.toJSON()));
return hitMen; //CANNOT REMEMBER WHY I PUT THIS HERE (NO SIDE EFFECTS)
}
});
});
I did not define the template in the view as template: , but instead I defined it inside the addNewHitJob property.
1. Is this correct? I did this because I will have more than one template. The said template is below
Template (in Jade), I can translate to html if need be
.span4#newHitJobForm
script#newHitJobTemplate(type="text/template")
select#names
{[ _.each(hitman, function(name) { ]}
option(value="{{ name._id }}") {{ name.name }}
{[ }); ]}
2. From what I have seen, My problem is with passing hitman to the template, but I am uncertain. Is there something I am missing?

Your evaluate regex isn't right, you want:
evaluate: /\{\[(.+?)\]\}/g
Your evaluate regex is equivalent to your interpolate since [\S\s] should match anything just like . does.
And when you call an Underscore template, you need to give it an object with the names and values for the template, just handing it an array (hitMen.toJSON()) won't do anything useful; you need to give your serialized hitMen a name so that the template can refer to them:
$('#newHitJobForm').html(template({ hitMen: hitMen.toJSON() }));
and then in the template:
{[ _.each(hitMen, function(hitMan) { ]}
option(value="{{ hitMan.cat._id }}") {{ hitMan.name }}
{[ }); ]}
I had to guess about the hitMan.cat._id part.

Related

How can I use interpolation to specify element directives?

I want to create a view in angular.js where I add a dynamic set of templates, each wrapped up in a directive. The directive names correspond to some string property from a set of objects. I need a way add the directives without knowing in advance which ones will be needed.
This project uses Angular 1.5 with webpack.
Here's a boiled down version of the code:
set of objects:
$scope.items = [
{ name: "a", id: 1 },
{ name: "b", id: 2 }
]
directives:
angular.module('myAmazingModule')
.directive('aDetails', () => ({
scope: false,
restrict: 'E',
controller: 'myRavishingController',
template: require("./a.html")
}))
.directive('bDetails',() => ({
scope: false,
restrict: 'E',
controller: 'myRavishingController',
template: require("./b.html")
}));
view:
<li ng-repeat="item in items">
<div>
<{{item.name}}-details/>
</div>
</li>
so that eventually the rendered view will look like this:
<li ng-repeat="item in items">
<div>
<a-details/>
</div>
<div>
<b-details/>
</div>
</li>
How do I do this?
I do not mind other approaches, as long as I can inline the details templates, rather then separately fetching them over http.
Use ng-include:
<li ng-repeat="item in items">
<div ng-controller="myRavishingController"
ng-include="'./'+item.name+'.html'">
</div>
</li>
I want to inline it to avoid the http call.
Avoid http calls by loading templates directly into the template cache with one of two ways:
in a script tag,
or by consuming the $templateCache service directly.
For more information, see
AngularJS $templateCache Service API Reference
You can add any html with directives like this:
const el = $compile(myHtmlWithDirectives)($scope);
$element.append(el);
But usually this is not the best way, I will just give a bit more detailed answer with use of ng-include (which actully calls $compile for you):
Add templates e.g. in module.run: [You can also add templates in html, but when they are required in multiple places, i prefer add them directly]
app.module('myModule').run($templateCache => {
$templateCache.put('tplA', '<a-details></a-details>'); // or webpack require
$templateCache.put('tplB', '<b-details></b-details>');
$templateCache.put('anotherTemplate', '<input ng-model="item.x">');
})
Your model now is:
$scope.items = [
{ name: "a", template: 'tplA' },
{ name: "b", template: 'tplB' },
{ name: "c", template: 'anotherTemplate', x: 'editableField' }
]
And html:
<li ng-repeat="item in items">
<div ng-include="item.template">
</div>
</li>
In order to use dynamic directives, you can create a custom directive like I did in this plunkr:
https://plnkr.co/edit/n9c0ws?p=preview
Here is the code of the desired directive:
app.directive('myProxy', function($compile) {
return {
template: '<div>Never Shown</div>',
scope: {
type: '=',
arg1: '=',
arg2: '='
},
replace: true,
controllerAs: '$ctrl',
link: function($scope, element, attrs, controller, transcludeFn) {
var childScope = null;
$scope.disable = () => {
// remove the inside
$scope.changeView('<div></div>');
};
$scope.changeView = function(html) {
// if we already had instanciated a directive
// then remove it, will trigger all $destroy of children
// directives and remove
// the $watch bindings
if(childScope)
childScope.$destroy();
console.log(html);
// create a new scope for the new directive
childScope = $scope.$new();
element.html(html);
$compile(element.contents())(childScope);
};
$scope.disable();
},
// controller is called first
controller: function($scope) {
var refreshData = () => {
this.arg1 = $scope.arg1;
this.arg2 = $scope.arg2;
};
// if the target-directive type is changed, then we have to
// change the template
$scope.$watch('type', function() {
this.type = $scope.type;
refreshData();
var html = "<div " + this.type + " ";
html += 'data-arg1="$ctrl.arg1" ';
html += 'data-arg2="$ctrl.arg2"';
html += "></div>";
$scope.changeView(html);
});
// if one of the argument of the target-directive is changed, just change
// the value of $ctrl.argX, they will be updated via $digest
$scope.$watchGroup(['arg1', 'arg2'], function() {
refreshData();
});
}
};
});
The general idea is:
we want data-type to be able to specify the name of the directive to display
the other declared arguments will be passed to the targeted directives.
firstly in the link, we declare a function able to create a subdirective via $compile . 'link' is called after controller, so in controller you have to call it in an async way (in the $watch)
secondly, in the controller:
if the type of the directive changes, we rewrite the html to invoke the target-directive
if the other arguments are updated, we just update $ctrl.argX and angularjs will trigger $watch in the children and update the views correctly.
This implementation is OK if your target directives all share the same arguments. I didn't go further.
If you want to make a more dynamic version of it, I think you could set scope: true and have to use the attrs to find the arguments to pass to the target-directive.
Plus, you should use templates like https://www.npmjs.com/package/gulp-angular-templatecache to transform your templates in code that you can concatenate into your javascript application. It will be way faster.

Passing keys of object to directive

I have created a directive as a wrapper for md-autocomplete so that it's easier to re-use. In the parent controller, I have an object. I want to pass the keys of the object to my custom directive, but I'm having trouble. Simplified code, without md-autocomplete:
Here's the script
var app = angular.module('myApp',[])
.controller('parentController', function(){
var parent = this;
parent.things = {item1: {color: "blue"}, item2: {color: "red"}};
})
.directive('childDirective',function(){
return {
scope: {},
bindToController: {
items:'&'
},
controller: childController,
controllerAs: 'child',
template: '<pre>{{child.items | JSON}}<pre>' //should be [item1,item1]
}
function childController(){
//Just a dummy controller for now
}
})
HTML
<div ng-app="myApp" ng-controller="parentController as parent">
<my-directive items="Object.keys(parent.things)">
</my-directive>
</div>
TL;DR: How do I pass the keys of an object defined in the parent controller to a child directive? I need to pass just the keys, not the object itself, because my directive is designed to deal with an array of strings.
Try using a directive with local scope from user attribute (=)
app.directive('childDirective', function() {
return {
replace: true,
restrict: 'E',
scope: {
items: '='
},
template: '<pre>{{items | JSON}}<pre>'
};
});
Using the directive, object in attribute "items" is passed "as is" , as a scope variable "items"
<div ng-app="myApp" ng-controller="parentController as parent">
<my-directive items="getKeys(parent.things)">
</my-directive>
</div>
Using Object.keys(obj) as source will cause an infinite loop digest (the function is always returning a new different object). You need a function to save the result to a local updatable object, like in this example:
https://jsfiddle.net/FranIg/3ut4h5qm/3/
$scope.getKeys=function(obj){
//initialize result
this.result?this.result.length=0:this.result=[];
//fill result
var result=this.result;
Object.keys(obj).forEach(function(item){
result.push(item);
})
return result;
}
I'm marking #Igor's answer as correct, because ultimately it led me to the right place. However, I wanted to provide my final solution, which is too big for a comment.
The search for the answer to this question led me to create a directive that is more flexible, and can take several different types of input.
The real key (and my actual answer to the original question) was to bind the items parameter to a proxy getter/setter object in the directive. The basic setup is:
app.directive('myDirective',function(){
return {
...
controller: localControl,
bindToController: {
items: '<' //note one-way binding
}
...
}
function localControl(){
var child = this;
child._items = [],
Object.defineProperties(child,{
items: {
get: function(){return child._items},
set: function(x){child._items = Object.keys(x)}
}
});
}
});
HTML
<my-directive items="parent.items">
<!-- where parent.items is {item1:{}, item2:{}...} -->
</my-directive>
Ultimately, I decided I wanted my directive to be able to accept a variety of formats, and came up with this plunk as a demonstration.
Please feel free to offer comments/suggestions on improving my code. Thanks!

Angular - Bind directive value to controller object

I'm trying to pass an array from a controller to a directive and for some (probably obvious to you lot!) reason when the array values are updated in the controller it does not reflect in the directive. The controller obtains data from a service into an array and I want to pass that array to the directive to create a bar graph. I've put the key parts of the code below.
Here is my top level HTML
<div dash-progress
graph-data="{{dashCtrl.myProgress}}">
</div>
<div>
Other Stuff
</div>
My template HTML for the directive:
<div class="boxcontent" ng-show="dashCtrl.showProgress">
<div class="chart-holder-lg">
<canvas tc-chartjs-bar
chart-data="progress"
chart-options="options"
height="200"
auto-legend>
</canvas>
</div>
</div>
Controller:
angular
.module('myApp')
.controller('dashCtrl',['mySvc',
function(mySvc) {
var self = this;
this.myProgress = [];
this.getProgress = function() {
//logic must be in the service !
mySvc.getProgress().then(function(success) {
self.myProgress = mySvc.progress;
});
};
}]);
and the directive:
angular
.module('myApp')
.directive('dashProgress', [function() {
return {
restrict: 'AE',
templateUrl: 'components/dashboard/progress.html',
scope: {
graphData: '#'
},
link: function(scope,el,attrs) {
scope.progress = {
labels: ['Duration','Percent'],
datasets: [
{
label: 'Duration',
data: [scope.graphData.duration]
},
{
label: 'Percent',
data: [scope.graphData.percent]
}
]
};
scope.options = { };
}
}
}]);
If I set an initial values of the myProgress object in the controller then these do get reflected in the directive, but I don't get the real values that I need when they are returned to the controller from the service.
In your directive's scope, instead of this:
scope: {
graphData: '#'
}
try using this:
scope: {
graphData: '='
}
Don't use {{ }} when passing array to the directive with =. It will render the array in the view instead of passing a reference to directive's scope.
As far as I know, # is not only one-way binding, but also one-time binding and should be used mostly for string values (e.g. setting an html attribute while initializing directive). If you'd like to use #, you should firstly convert data to JSON, then pass it to directive with {{ }}, then parse it again in directive and after any change - manually recompile the directive. But it would be a little overkill, wouldn't it?
Conclusion
Just remove the curly brackets from the view and use = to bind value to directive's scope.
View
<div dash-progress
graph-data="dashCtrl.myProgress">
</div>
Directive
scope: {
graphData: '='
},
Update
Try one more thing. In dashCtrl, wrap myProgress with an object (you can change names to be more self-explaining - this is just an example):
this.graphData = {
myProgress: []
}
this.getProgress = function() {
mySvc.getProgress().then(function(success) {
self.graphData.myProgress = mySvc.progress;
});
}
Then, pass graphData to directive:
<div dash-progress
graph-data="dashCtrl.graphData">
</div>
Finally, substitute every scope.graphData with scope.graphData.myProgress. This way you make sure that scope.graphData.myProgress always refers to the same data because it's a property of an object.
If this still doesn't work, you will probably have to use a watcher and update properties of scope.progress manually.

Angular: How do I dynamically add ng-hide to a template that was loaded via templateUrl?

I'm trying to build a directive that reduces boilerplate for text fields, where the server-side declarations of things like field visibility can be passed in via a model.
I want to load the HTML for a general field from a templateUrl, transform the DOM of that (adding in various attributes and directives to this template) according to the model.
I've got it binding the proper ng-model to the nested input field, but when I try to apply an ng-hide to the top-level element, it shows up in the DOM but does no take effect.
If it were working properly, the code (so far) should be hiding the field, but it is not.
The code is at http://jsbin.com/AHoLAnUg/1/edit, and is reproduced below:
angular.module("directives", []).
directive('tuTextField',
function() {
return {
restrict: 'E',
replace: true,
compile: function(ele, attr) {
var element = jQuery(ele);
var input = jQuery(element.children('input')[0]);
// These work:
element.attr('id', attr.id);
element.attr('class', attr['class']);
// this fails: (I've tried element.attr() as well)
attr.$set('ngHide', attr.model + ".invisible['" + attr.field + "']");
// but this WORKS:
input.attr("ng-model", attr.model + ".fields." + attr.field);
},
templateUrl: '/AHoLAnUg/1.css'
};
}).
controller('v', [ '$scope', function(scope) {
scope.state = {
fields: {
name: "Tony"
},
invisible: {
name: true
},
readonly: {
name: true
},
validations: {
name: {
pattern: "^[a-zA-Z]",
message: "Must begin with a letter"
}
}
};
}]);
You shouldn't manipulate the root element of directive because compile function is called after $compile service finish its job, but you CAN manipulate child elements since they'll be compiled after their parent.
This is an example for directive execution order:
jsFiddle
That's why ngHide in your example won't take effect but ngModel will.
Try wrapping your template with another and manipulate them as you want.

BackboneJS with HandelbarJS: How to access model functions?

I am exploring a setup with HandelbarsJS and Backbone.
This is part of my template:
<a href="#genre/{{ name }}" class="genre-item" data-genre="{{ name }}">
<i class="icon-chevron-{{#if is_selected }}down{{else}}right{{/if}}"></i>
{{ display_name }} ({{ total }})
</a>
Meaning: I want to render a different icon, depending on whether a model is selected or not.
However, I never get the 'icon-chevron-down', but always the 'icon-chevron-right' path.
Any ideas what I am missing?
EDIT
The selection of a Genre is working on model level like this:
MA.Models.Genre = Backbone.Model.extend({
defaults: {
selected: false
},
is_selected: function() {
return (this.get('selected') == true);
},
toggle: function() {
if (this.is_selected()) {
this.set('selected', false);
}
else
{
this.set('selected', true);
}
}
});
MA.Collections.Categories = Backbone.Collection.extend({
model: MA.Models.Genre
});
This could probably be simplified, but I am not getting the selection of the Genre from the remote service, but it is used just as a temporary state change.
Without seeing what is happening in your view it's hard to tell. But you probably have a render function that look's like:
HandlebarsTemplate['templatename'](this.model.toJSON());
toJSON by default only includes model attributes. Also handlebars won't evalute functions on the fly like that.
The easiest solution is to fix the template to look like:
<a href="#genre/{{ name }}" class="genre-item" data-genre="{{ name }}">
<i class="icon-chevron-{{#if selected }}down{{else}}right{{/if}}"></i>
{{ display_name }} ({{ total }})
</a>
I've changed is_selected to selected to use the attribute instead of the function.
The other option is to modify the toJSON function of the model to include the evaluated function:
MA.Models.Genre = Backbone.Model.extend({
defaults: {
selected: false
},
is_selected: function() {
return (this.get('selected') == true);
},
toJSON: function(options) {
var attrs = _.clone(this.attributes);
attrs.is_selected = this.is_selected();
return attrs;
}
});

Resources