Instantiate a module directive asynchronously using AngularJS and HeadJS - javascript-framework

I created a custom directive attribute that will turn an ordinary select box into a ChosenJS (http://harvesthq.github.com/chosen/) select box. To make the code cleaner, I want to load the external chosen.js plugin file asynchronously with HeadJS. Here is my AngularJS directive:
myApp.module.directive('chosen-select', function() {
head.js(myApp.pathTo.plugin.chosen);
head.ready(function() {
var linker = function(scope, element, attr) {
element.chosen();
}
return {
restrict: 'A',
link: linker
}
})
});
The problem I'm having is that it seems that because I am loading it asynchronously, Angular doesn't know it exists and the directive is not working. Is there a way to programmatically inject a dynamically loaded module directive so that Angular knows about it and can update the view accordingly?

In your example, directive function isn't returning a config object for the directive that's why it is failing.
Try this:
var myApp = angular.module('myApp', []);
myApp.directive('chosenSelect', function() {
var el;
// load chosen file
head.js(myApp.pathTo.plugin.chosen);
head.ready(function() {
jQuery(el).chosen();
});
return {
restrict: 'A',
link: function(scope, element, attr) {
// set el via closure, so that head ready callback has access to it
el = element;
}
};
});

Related

Update global variable on scroll event angular 5

I'm working on angular 5 application. I want to update a variable when the page is scrolling, but the problem is when I put console log inside the scope, the variable is updated but in Dom is not.
component:
#HostListener('window:scroll') public windowScrolling(): void {
this.isMenuOpen = false;
console.log(this.isMenuOpen) // false }
DOM:
{{isMenuOpen}} // true
I guess the variable inside the scope becomes local variable but I have no idea how to make it global on scroll event. I really appreciate if somebody has any solution.
**Implement like this**.
ngOnInit() {
window.addEventListener('scroll', function (e) {
this.scroll(e);
}.bind(this), true);
}
scroll(event: any) {
console.log(event)
this.isMenuOpen = false;
console.log(this.isMenuOpen)
}

Knockout SPA Ajax loaded templates

I am lost between the possibilities offered to handle this case: let's say we have the following constraints:
Knockout
SPA with Sammy.js - Html loaded via Ajax
My page:
+-------------------------------+
| #navigation |
+---------+---------------------+
| #sidebar| #content |
| | |
| | |
| | |
+---------+---------------------+
Currently, I have one appViewModel which handle the data-bind for all the shared elements of my website: #navigation and #sidebar. This appViewModel has observable used on every pages of my website.
appViewModel = function () {
var self = this;
self.sidebarItemArray = ko.observableArray([x, y, z]);
self.currentRoute = ko.observable();
...
self.updateView = function(path, currentRoute) {
return $.get(path, function( data ) {
var $data = $(data);
// Updates #content, TITLE and update the currentRoute observable.
$( '#content' ).replaceWith($data.find('#content'));
document.title = $data.filter('title').text();
self.currentRoute(currentRoute);
}, 'html');
}
Sammy(function() {
this.get(':link'', function() {
self.updateView(this.path, this.params.link);
});
}).run();
}
ko.applyBindings(new appViewModel());
Now, let's say that #content is a piece of DOM loaded through an Ajax Call. Each time a user click a link inside #navigation or #sidebar, Sammy.js intercept it and then update #content. The problem is that the new DOM inside #content has data-bindings itself.
1) First, should I use the html data-bind on #content, replaceWith(as above) or the template binding with custom function to get the template?
(http://knockoutjs.com/documentation/template-binding.html#note-5-dynamically-choosing-which-template-is-used)? What is the best practice here?
2) Should Sammy necessary lives inside the appViewModel as in the documentation or elsewhere is just fine?
3) Once the updateView method is completed, how would you bind the new DOM? Like below? Isn't there a risk of rebinding some DOM because ko.applyBindings has already been called without second argument?
ko.applyBindings(new routeSpecificViewModel() , document.getElementById("content"));
I am thankful for your help.
One simple solution is to make the page's viewmodel an observable, and load it ondemand. Use a variable to record if ko.applyBindings has been called. Example from the knockout-spa framework:
/*! knockout-spa (https://github.com/onlyurei/knockout-spa) * Copyright 2015-2016 Cheng Fan * MIT Licensed (https://raw.githubusercontent.com/onlyurei/knockout-spa/master/LICENSE) */
define(['app/shared/root-bindings', 'framework/page-disposer', 'ko', 'sugar'], function (
RootBindings, PageDisposer, ko) {
var initialRun = true;
var Page = {
init: function (name, data, controller, path) {
Page.loading(false);
name = name.toLowerCase();
if ((Page.page().name == name) && (Page.page().data == data)) { // if the requested page is the same page, immediately call controller without going further
if (controller) {
controller(data);
}
document.title = Page.title();
if (Page.initExtra) {
Page.initExtra(name, data, controller);
}
return data;
}
var autoDispose = (Page.page().data.dispose && Page.page().data.dispose(Page)) || true; // if the requested page is not the same page, dispose current page first before swap to the new page
if (autoDispose !== false) {
// auto-dispose page's exposed observables and primitive properties to initial values. if not desired, return
// false in dispose function to suppress auto-disposal for all public properties of the page, or make the
// particular properties private
PageDisposer.dispose(Page.page().data);
}
PageDisposer.init(data); //store initial observable and primitive properties values of the page
var initialized = (data.init && data.init(Page)) || true; // init view model and call controller (optional) before template is swapped-in
if (initialized === false) {
return false; // stop initialization if page's init function return false (access control, etc.)
}
if (controller) {
controller(data);
}
Page.pageClass([name, ('ontouchstart' in document.documentElement) ? 'touch' : 'no-touch'].join(' '));
Page.page({
name: name,
data: data,
path: path
}); // to test if template finished rendering, use afterRender binding in the template binding
document.title = Page.title();
if (Page.initExtra) {
Page.initExtra(name, data, controller); // useful for common init tasks for all pages such as anaylitics page view tracking, can be set in RootBindings
}
if (initialRun) {
ko.applyBindings(Page, document.getElementsByTagName('html')[0]); // apply binding at root node to be able to bind to anywhere
initialRun = false;
}
return data;
},
page: ko.observable({
name: '', // name of the page - auto-set by the framework, no need to worry
data: {
init: function () {}, // preparation before the page's template is rendered, such as checking access control, init/instantiate modules used by the page, etc.
dispose: function () {} // properly dispose the page to prevent memory leaks and UI leftovers (important for SPA since page doesn't refresh between page views) - remove DOM element event listeners, dispose knockout manual subscriptions, etc.
}
}),
pageClass: ko.observable(''),
loading: ko.observable(false),
title: function () {
return Page.page().name.titleize(); // override in RootBindings as needed
}
};
Object.merge(Page, RootBindings); // additional root bindings as needed by the app
return Page;
});
A mini but full-fledged SPA framework built on top of Knockout, Require, Director, jQuery, Sugar.
https://github.com/onlyurei/knockout-spa
Live Demo: https://knockout-spa.mybluemix.net

hash in url to deep linking with ajax

I've this code to load content in a div #target with some animation. Works fine but i don't know how implement code to change link and url with #hash!
How can I do this?
the code:
$(document).ready(function(){
$("#target").addClass('hide');
$('.ajaxtrigger').click(function() {
var pagina = $(this).attr('href');
if ($('#target').is(':visible')) {
}
$("#target").removeClass('animated show page fadeInRightBig').load(pagina,
function() {
$("#target").delay(10).transition({ opacity: 1 })
.addClass('animated show page fadeInRightBig');
}
);
return false;
});
});
Try to use any javascript router. For example, router.js.
Modify you code like this(I didn't check if this code work, but I think idea should be clear):
$(document).ready(function(){
var router = new Router();
//Define route for your link
router.route('/loadpath/:href', function(href) {
console.log(href);
if ($('#target').is(':visible')) {
$("#target").removeClass('animated show page fadeInRightBig').load(href,
function() {
$("#target").delay(10).transition({ opacity: 1 })
.addClass('animated show page fadeInRightBig');
}
);
}
});
router.route('', function(){ console.log("default route")});
$("#target").addClass('hide');
// Instead of loading content in click handler,
// we just go to the url from href attribute with our custom prefix ('/loadpath/').
// Router will do rest of job for us. It will trigger an event when url hash is
// changes and will call our handler, that will load contents
// from appropriate url.
$('.ajaxtrigger').click(function() {
router.navigate('/loadpath/' + $(this).attr('href'));
return false;
});
});

KendoUI DataSource binding to MVVM grid in durandal (using hottowel template) doesn't seem to work

I am using Visual Studio 2012 Update 2 hottowel template with updated durandal and jquery nuget packages...
Here is my code:
Durandal main.js:
require.config({
paths: { "text": "durandal/amd/text" }
});
define(['durandal/app', 'durandal/viewLocator', 'durandal/viewModelBinder', 'durandal/system', 'durandal/plugins/router', 'services/logger'],
function (app, viewLocator, viewModelBinder, system, router, logger) {
// Enable debug message to show in the console
system.debug(true);
app.start().then(function () {
toastr.options.positionClass = 'toast-bottom-right';
toastr.options.backgroundpositionClass = 'toast-bottom-right';
router.handleInvalidRoute = function (route, params) {
logger.logError('No Route Found', route, 'main', true);
};
// When finding a viewmodel module, replace the viewmodel string
// with view to find it partner view.
router.useConvention();
viewLocator.useConvention();
// Adapt to touch devices
app.adaptToDevice();
kendo.ns = "kendo-";
viewModelBinder.beforeBind = function (obj, view) {
kendo.bind(view, obj.viewModel || obj);
};
//Show the app by setting the root view model for our application.
app.setRoot('viewmodels/shell', 'entrance');
});
});
Durandal viewmodel:
define(['services/datacontext', 'durandal/plugins/router'],
function (datacontext, router) {
var activate = function () {
//yes yes - I will separate this out to a datacontext - it is here for debugging simplicity
var service = $data.initService("https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase/");
//return promise as durandal seems to want...
return service.then(function (db) {
vm.set("airports", db.Airport.asKendoDataSource());
});
};
var deactivate = function () {
};
var viewAttached = function (view) {
//kendo.init($("#airportGrid"));
//kendo.bind(view, vm);
//kendo.bind($("#airportGrid"), vm);
};
var vm = new kendo.data.ObservableObject({
activate: activate,
deactivate: deactivate,
airports: [],
title: 'Airports',
viewAttached: viewAttached
});
return vm;
});
Durandal view:
<section>
<h2 class="page-title" data-bind="text: title"></h2>
<div id="airportGrid" data-kendo-role="grid" data-kendo-sortable="true" data-kendo-pageable="true" data-kendo-page-size="25" data-kendo-editable="true" data-kendo-columns='["id", "Abbrev", "Name"]' data-kendo-bind="source: airports"></div>
</section>
I see the call being made to jaystack in Chrome's network monitor:
https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase//Airport?$inlinecount=allpages&$top=25
And I see data coming back.
The kendoui grid is created nicely but there is no data in it (I think this means kendoui is happy and the MVVM bindings are being bound to, however the created kendoui grid doesn't seem to want to understand the kendoui datasource created from jaydata)
Without durandal this works just nicely as demonstrated in:
http://jsfiddle.net/t316/4n62B/29/
I have been trying and trying for 2 days now - can someone please help me out?
Thanks
TJ
Sounds like everything is working now after removing the parts that are only required by breeze.
Nevertheless I'd suggest restructuring the working dFiddle code slightly to ensure that a) vm is defined before setting vm.airports in activate and b) there's no need to create a dummy vm.airports kendo.data.DataSource() that gets overwritten in activate anyway.
define(function( ) {
var vm = new kendo.data.ObservableObject({
activate: activate,
deactivate: deactivate,
// airports: new kendo.data.DataSource(),
title: 'Airports',
viewAttached: viewAttached
});
return vm;
function activate () {
var service = $data.initService("https://open.jaystack.net/c72e6c4b-27ba-49bb-9321-e167ed03d00b/6494690e-1d5f-418d-adca-0ac515b7b742/api/mydatabase/");
return service.then(function( db ) {
vm.airports = db.Airport.asKendoDataSource();
});
}
function deactivate () {
}
function viewAttached ( view ) {
//kendo.init($("#airportGrid"));
//kendo.bind(view, vm);
//kendo.bind($("#airportGrid"), vm);
}
});
Which version on jQuery do you use? Try with 1.8.3 or 1.9 + Migration.
In Chrome switch the stop sign to purple (two clicks) to catch uncaught exceptions and see if there is any.

Is Backbone.js suitable for getting HTML from server?

As far as I can tell, Backbone.js view represents DOM element. I take it from existing DOM or create it on the fly in el attribute.
In my case, I want to take it from server with AJAX request because I'm using Django templates and don't want to rewrite everything to JavaScript templates.
So I define el function that performs AJAX request.
el: function() {
model.fetch().success(function(response) {
return response.template
})
}
Of course, it does NOT work because AJAX request is executed asynchronous.
This means that I don't have el attribute and events does NOT work neither. Can I fix it?
Maybe the Backbone.js framework isn't the right tool for my needs? The reason I want to use that was to have some structure for the code.
P.S. I'm new to Backbone.js.
Do your ajax request from another view, or directly after the page load using jquery directly, and after you've downloaded your template, THEN instantiate your backbone view class with the proper id/el or whatever (depending on where you stored your ajax fetched template). Depending on your use-case, this may or may not be a sensible approach.
Another, perhaps more typical approach, would be to set up your view with some placeholder element (saying "loading" or whatever), then fire off the ajax, and after the updated template has been retrieved, then update your view accordingly (replace the placeholder with the actual template you requested).
When/if you update your view with new/other DOM elements, you need to call the view's delegateEvents method to rebind your events to the new elements, see:
http://backbonejs.org/#View-delegateEvents
I came across a similar requirement. In my instance, I was running asp.net and wanted to pull my templates from user controls. The first thing I would recommend is looking into Marionette because it will save you from writing a lot of boiler plate code in Backbone. The next step is to override how your templates are loaded. In this case I created a function that uses Ajax to retrieve the HTML from the server. I found an example of this function where they were using it to pull down html pages so I did a little modification so I can make MVC type requests. I can't remember where I found the idea from; otherwise, I would give the link here.
function JackTemplateLoader(params) {
if (typeof params === 'undefined') params = {};
var TEMPLATE_DIR = params.dir || '';
var file_cache = {};
function get_filename(name) {
if (name.indexOf('-') > -1) name = name.substring(0, name.indexOf('-'));
return TEMPLATE_DIR + name;
}
this.get_template = function (name) {
var template;
var file = get_filename(name);
var file_content;
var result;
if (!(file_content = file_cache[name])) {
$.ajax({
url: file,
async: false,
success: function (data) {
file_content = data; // wrap top-level templates for selection
file_cache[name] = file_content;
}
});
}
//return file_content.find('#' + name).html();
return file_content;
}
this.clear_cache = function () {
template_cache = {};
};
}
The third step would be to override Marionette's method to load templates. I did this in the app.addInitializer method. Here I am initializing my template loader and setting it's directory to a route handler. So when I want to load a template, I just set the template: "templatename" in my view and Backbone will load the template from api/ApplicationScreens/templatename. I am also overriding my template compiling to use Handlebars because ASP.net is not impressed with the <%= %> syntax.
app.JackTemplateLoader = new JackTemplateLoader({ dir: "/api/ApplicationScreens/", ext: '' });
Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (name) {
if (name == undefined) {
return "";
} else {
var template = app.JackTemplateLoader.get_template(name);
return template;
}
};
// compiling
Backbone.Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate) {
var compiled = Handlebars.compile(rawTemplate);
return compiled;
};
// rendering
Backbone.Marionette.Renderer.render = function (template, data) {
var template = Marionette.TemplateCache.get(template);
return template(data);
}
Hopefully this helps. I've been working on a large dynamic website and it is coming along very nicely. I am constantly being surprised by the overall functionality and flow of using Marionette and Backbone.js.

Resources