Wednesday, December 10, 2014

require.js conflicts with chart.js when AMD loading

When attempting to use chart.js on my web site, the chart would not load correctly and the following error appeared in the browser console:
Error: Mismatched anonymous define() module: function (){
"use strict";
return Chart;
}
http://requirejs.org/docs/errors.html#mismatch
The problem arises when using an AMD loader for JavaScript modules and the fact that the chart.js source is an anonomous function (like follows):
 (function(){
// code in here
}).call(this);
The solution is not to reference the chart.js in the HTML markup but to simply  require and use it when needed (when interacting with the charts) in the jQuery.
require(['path/to/Chart.js'], function(Chart){
// Use Chart.js as normal here.

// Chart.noConflict restores the Chart global variable to it's previous owner
// The function returns what was previously Chart, allowing you to reassign.
var Chartjs = Chart.noConflict();
});
Don't forget to remove any references to chart.js in the HTML or the errors will still occur.

AngularJS grouping radio buttons on a form

HTML input elements of radio button type are grouped together using the name attribute. With AngularJS forms (and form validation), the name attribute is generally set as a unique identifier. To get grouped radio buttons to work correctly on a form using AngularJS you simply need to set a value to each radio button.


In the example above the two checkboxes are in the same group and share the same angular model. The active value controls which one is set to checked - although this is in textual form and not numeric.

jQuery replace all spaces in a string

In jQuery to replace all occurrences of a space in a given string (and not just the first one), the following code will work.
var myString = "a simple string";
myString.replace(/ /g, '');
in this example the string will go from "a simple string" to "asimplestring".