• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Wednesday, 20 Mar 2013 14:47

If you attempt to load data from an external domain into a Fiddle you’re likely going to receive an XMLHttpRequest error that looks something like “Origin is not allowed by Access-Control-Allow-Origin”. You can use JSFiddle’s echo requests if you just want to simulate returning data, but sometimes you want to demonstrate an actual retrieval.

Legitimate security concerns regarding cross-site HTTP requests are the reason why you can’t simply read in any old file. However, using appropriate page headers makes accessing files from other domains possible. So, if we can set page headers in a file that returns our data, it should be accessible, right? Right!

This can’t be done using a JSON file, but it can be done in a PHP file that is setup to output JSON. The PHP code would look something like this:

<?php
// Allow access from anywhere. Can be domains or * (any)
header('Access-Control-Allow-Origin: http://fiddle.jshell.net');

// Allow these methods of data retrieval
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

// Allow these header types
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

// Create our data object in that crazy unique PHP way
$arr = array(array("id" => 1, "character" => "Minstrel", "line" => "And Saint Attila raised the hand grenade up on high, saying, 'O Lord, bless this thy hand grenade, that with it thou mayst blow thine enemies to tiny bits, in thy mercy.' And the Lord did grin."));

// Return as JSON
echo json_encode($arr);
?>

Note that you don’t have to use PHP. You can use just about any server side scripting language; ASP, .NET, ColdFusion, Ruby, etc., as long as you set the headers properly.

Check out an example:

[There is a JSFiddle embedded in this post. Please follow the link below or go to the site to see this JSFiddle.]

View this on JSFiddle

Author: "rabidgadfly" Tags: "Uncategorized, cross-domain, fiddle, hea..."
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 14 Mar 2013 17:05

I’ve experienced some frustration recently with all of the big three code sandboxes: JSFiddle, Plunker, and CodePen. I’d originally picked Plunker because it provides the ability to create separate datasource files that can be used in my Plunks. This is extremely useful, especially when demonstrating how to load an external data source.

About a week ago while viewing my own post in Appliness digital magazine (shameless plug) I noticed that I couldn’t access the source code in the embedded iFrame. I wasn’t sure if this was an oddity with Appliness so I made a mental note to check it out.

The very next day I received a comment from a visitor stating that they were having the same problem when viewing the site on their phone. Obviously, I had a problem. I want my code to be viewable on as many devices as possible so I started looking into alternatives.

CodePen

ferrari

For looks, you can’t beat CodePen. It’s definitely the Ferrari of the bunch. Its sleek black skin and optional upgrades made me want to take it for a spin. The CodePen window is made up of four frames, HTML, CSS, JS, and the Output. Each code frame has its own set of additional features/libraries accessible via a small gear icon in the upper right corner.

CodePen’s additional features are very slick and useful. The HTML frame allows you to utilize three useful templating tools, Haml, Markdown and Slim, at the click of a button. CSS provides easy access to Less and Sass as well as some other oft-used CSS functionality, like reset. And JS frame applies clickable access to Coffeescript and Modernize, as well as allowing you to add any external library of your choosing. It also provides a useful link to cdnjs.com where you can find a CDN reference to just about any library yo can think of.

CodePen

CodePen felt great, looked great, and provided optional upgrades. Unfortunately, once you take it out of the garage and park it in your driveway, i.e., embed it on your site, it doesn’t necessarily run great.

fiero

As a matter of fact, my Angular code which works when viewed on CodePen, did not work at all on my site. The Ferrari of sandboxes actually seems more like a Fiero with a Ferrari kit.

JSFiddle

minivan

JSFiddle seems to be the most widely-used sandbox. It’s the most utilitarian of the three…the minivan, if you will. Its looks are very basic, and while it claims the ability to apply different skins when embedded, the only skins available are “light” (light gray and white) and “presentation” (light gray and white with a gigantic font). You would think if there was a “light” there would also be a “dark”, right? Nope. This minivan only comes in gray.

Like CodePen, JSFiddle displays HTML, JS, CSS, and output frames. It provides access to a slew of libraries via a too-huge dropdown list. It also provides a second dropdown with esoteric options like “no wrap – in head”, which actually turns out to be quite important. The rest of the options are hidden in a vertical accordion.

jsfiddle

The most important difference between CodePen and JSFiddle, however, is only apparent when it’s embedded. JSFiddle works and CodePen doesn’t.

Plunker

buick

Plunkr is a little different than the others. It’s no Ferrari, but it’s no minivan either. I guess it’s a Buick. It’s looks are more modern than JSFiddles, but its options are almost non-existent. The window only has two frames: code and output. You create your own files rather than using dedicated HTML, JS, and CSS frames. While this means that you can’t look at all of your code at once, it actually lends to its flexibility.

With Plunkr you can create multiple files in the same project. This means you can test more abstractly, and easily swap functionality in and out. Your HTML head is in your code window making it easy to see what’s getting loaded. Being able to create your own files also means being able to create external datasources, which is fantastic for playing with dataloading functionality.

plunker

The biggest problem with Plunker is the one I mentioned earlier. When it’s embedded, you can’t view the source files on mobile devices.

So, what do you drive, a Fiero/Ferrari, a minivan, or a Buick? Or something entirely different?

Author: "rabidgadfly" Tags: "conversationStarter, Uncategorized, code..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 05 Mar 2013 17:18
This entry is part 9 of 9 in the series: AngularJS Learning Series

Check it out!

Learning Angular has been a fantastic experience so far. I’ve been consistently surprised at the results I can get from a screenful of code. This week’s Image Gallery experiment was no different. Before I get into the particulars, let’s take a look at the finished product:

If you check out the source app.js on that example you’ll notice that the JavaScript adds up to about 25 lines of code, half of which are dedicated to loading and setting the data source. Yes, there’s some CSS3 transition coolness thrown in, but even that is minimal.

So How Does It Work?

The gallery is made up of three sections: the main image, the caption, and the thumbnails. If you compare the main image section and the thumbnail section you’ll see that they’re very similar. The main difference being the size of the image how many of the image you can see:

<div class="mainimageshell">
    <div class="viewwindow">
        <ul id="fullscroller" class="fullsizelist" ng-style="listposition" >
            <li ng-repeat="image in galleryData">
                <img id="fullsize" class="large" ng-src="{{image.image}}" />
            </li>
        </ul>
    </div>
</div>

<div class="captionshell">
    <p class="caption">{{selected.desc}}</p>
</div>

<div class="thumbsshell">
    <div class="thumbswrapper">
        <ul>
            <li ng-repeat="image in galleryData">
                <div class="thumbwrapper">
                    <a ng-href="" ng-click="scrollTo(image,$index)">
                        <img class="thumbnail" ng-src="{{image.image}}" />
                    </a>
                </div>
            </li>
        </ul>
    </div>
</div>

If you were to comment out the overflow line of the viewwindow class you would see all of the images lined up side by side, just like the thumbnails.

When iterating over the data using ng-repeat, $index will reflect the zero-based index of each item. Since we’re looping over the same data, the index for both the large image and the thumbnail will be the same. This allows me to multiply the index by the width of the images to arrive at the new positioning for the large image list. Once I specify the new positioning, my CSS handles the transition, something like this:

ul.fullsizelist{
    position:absolute;
    top:0;
    left:0;
    transition:  left .8s ease;
}

Thanks to Angular, notifying the DOM element of its new position is ultra-simple. If you take a look at the fullscroller UL inside the template you’ll see that it contains the Angular ng-style directive and that it’s bound to the listposition property. Listposition is updated in the scrollTo function every time a thumbnail is clicked and any change is immediately reflected in the view:

// Scroll to appropriate position based on image index and width
$scope.scrollTo = function(image,ind) {
    $scope.listposition = {left:(IMAGE_WIDTH * ind * -1) + "px"};
    $scope.selected = image;
}

In addition to modifying the viewwindow position, the scrollTo function also assigns the currently selected item to $scope.selected. If you look at the template you’ll see that caption is rendering “{{selected.desc}}”. When $scope.selected is changed, the caption will automatically change with it.

Full Disclosure

My original idea was to fade out the old image and fade in the new image when a thumbnail was clicked. This worked great on Chrome, but Firefox would flash the image on screen once loaded and wouldn’t transition in properly. It also required transition end listeners, which at the moment are not standard across browsers. That meant separate listeners for each browser engine.

The whole thing was becoming a hassle and the code was getting unruly. That’s when I made the decision to switch to a slider and it worked out great. Point being, don’t be afraid to experiment or refactor. Oftentimes the best coding decisions are born out of a change in approach.

Author: "rabidgadfly" Tags: "angularJS, angular, css3, example, galle..."
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 20 Feb 2013 17:58
This entry is part 7 of 9 in the series: AngularJS Learning Series

The Finished Product

JSON is a native object to AngularJS so working solely with JSON examples is easy. In the real world, however, you’ll probably need to deal with other types of data sources, like XML. Before I get too wordy, let’s start with what you’re really here for…the example:

The Explanation

While the finished product looks like the result of 15 minutes of coding, I have to admit that it took me significantly longer to figure out. If you search the Angular Developer Guide or API for “XML” you’re going to come up woefully absent of useful results. Googling won’t get you much further. As frustration began to set in, I started thinking about what made loading an XML file more difficult than loading a JSON file. The answer is: not much!

Bridging the Language Gap

Angular likes JSON, and can you blame it? Angular is a JavaScript toolset and JSON is JavaScript Object Notation, a native brethren. XML, on the other hand, is tag-based markup…a foreign language to Angular. What I needed was a way to make Angular understand what XML was trying to communicate.

The key to overcoming any language gap is to have a translator. If there were a way to translate XML to JSON before handing it to the application then I could eliminate the language gap, and the problem.

A quick search for xml converters turned up multiple results. I chose Abdulla Abdurakhmano’s X2JS library because it was the first one I came across, it was lightweight, and it was pretty easy to use.

The code required to perform the translation is short and simple. Provide the library with XML, tell it which method to use, and receive JSON in return:

function(xml) {
 var x2js = new X2JS();
 var json = x2js.xml_str2json( xml );
 return json;
}

Where to Stick It

Now that I had a solution to the language gap I needed to decide where to implement it. Angular’s $http service conveniently applies transformation functions for both requests and responses. These functions apply transformations to data when it is sent and received, and they can be overridden.

Using the X2JS conversion code as a transformResponse function it was simple to get the $http service to read in XML and return JSON to the application, effectively creating the translator I needed. The results look something like this:

angular.module('myApp.service',[]).
    factory('DataSource', ['$http',function($http){
       return {
           get: function(callback){
                $http.get(
                    'data.xml',
                    {transformResponse:function(data) {
                    	// convert the data to JSON and provide
                    	// it to the success function below
						var x2js = new X2JS();
						var json = x2js.xml_str2json( data );
						return json;
						}
					}
                ).
                success(function(data, status) {
					// send the converted data back
					// to the callback function
                    callback(data);
                })
           }
       }
    }]);
    
angular.module('myApp',['myApp.service']);

var AppController = function($scope,DataSource) {
    
    //This is the callback function
    setData = function(data) {
        $scope.dataSet = data;
    }
        
    DataSource.get(setData);
    
}

That’s really all there is to it! The example above will retrieve an xml file named “data.xml”, convert it to JSON, and assign the results to $scope.dataSet.

The Caveat

XML comes in all shapes and sizes. Some use attributes, others don’t, and many use a combination of both. Some XML files use a proper header, others are just fragments. Your application will likely require tweaking to get the data into the shape that your application requires. Always read the docs, read the comments, and experiment.

The example at the beginning of this post is a great starting point. Fork it and experiment with different libraries or XML formats.

Keep on Coding!

Author: "rabidgadfly" Tags: "angularJS, angular, http, javascript, XM..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 12 Feb 2013 17:20
This entry is part 5 of 9 in the series: AngularJS Learning Series

The Assignment

This week’s self-imposed Angular assignment was to create a small app that would dynamically filter a list of data using an input field as search criteria. I chose to base the app on my son’s homework assignment and use United States states and capitals.

In my previous examples I used Controllers for all functions and assignments. For simple non-critical applications the configuration works well, but for larger real-world applications a more abstract approach makes sense. Enter Angular Modules.

The Basics

Modules initialize Angular applications and wire together its services, filters, directives, etc. This makes the code portable, easier to debug, and easier to unit test.

To keep things simple, I only used a service in this example. The service is a gofer, responsible for carrying out any requests made by the controller. The controller sets scope properties and behaviors and handles calls from the template.

Here’s a basic module, service, and controller in Angular:

angular.module('myApp.service',[]);
angular.module('myApp',['myApp.service']);
var StatesController = function($scope) {}

On the first line is a service named ‘myApp.service’. Note that the dot is not necessary, nor is using the app name as a prefix. I could have named it ‘gofer’ if I wanted. The important part is that I let the main application module know the name, which brings me to line 2, the main module.

The main module names the app and gives it a a comma delimited reference to services, filters, etc. that can be referenced. If I defined a filter named ‘myApp.filter’ my module definition would have been: “angular.module(‘myApp’,['myApp.service','myApp.filter']);”. The module name, “myApp”, will be used in my ngApp directive in the template.

Line 3 is the shell of a controller definition which will be directly accessible by the template. While it wouldn’t do anything at this point, we could hook those three lines up to a template and assign myApp to the ngApp directive without error.

Let’s Get Some Data!

As with most applications, we’ll need access to data. My data source is a JSON file that looks like this:

[
    {"name":"Alabama", "capital":"Montgomery","abbreviation":"AL"},
    {"name":"Alaska", "capital":"Juneau","abbreviation":"AK"},
    {"name":"Arizona", "capital":"Phoenix","abbreviation":"AZ"},
    {"name":"Arkansas", "capital":"Little Rock","abbreviation":"AR"},
    ...
]

I need a way to create a resource object out of that data so I can interact with it. Angular’s ngResource module provides exactly what I need in its $resource service.

NOTE: The ngResource module is NOT in the base angular.js file. To use it you must load angular-resource.js in addition to angular.js. If you get an error in your debugging console that says “Uncaught Error: No module: ngResource”, chances are you forgot to load angular-resource.js. You do use a developer tools, right?

To retrieve the resource I utilized a method used to create objects in Angular called a factory. When I put the factory method inside my service, and then provide my Controller with a reference to it, I can use it in my controller to set a scoped property, like this:

angular.module('myApp.service',['ngResource']).
    factory('States', function($resource){
        return $resource('states.json', {},{
            get: {method: 'GET', isArray:true}
        });
    });

angular.module('myApp',['myApp.service']);

var StatesController = function($scope,States) {
    $scope.stateData = States.get();
};

So, what changed? First, I gave my service a reference to Angular’s ngResource module. That will give me the ability to use the $resource service for my factory allowing me to interact with my data source, “states.json”. Notice that the factory has a name, “States” which I provide to my Controller. From there I can access actions inside the factory, such as “get”, “save”, and “delete”.

Now, if I create a template referencing the controller I can display the data using my stateData property. Check out the source code here:

Make Something Angulary Happen

We now have a working module, a service, a factory, a controller, and data. Time to do something slick with it. Building off the html above, Inside my StatesController DIV I’m going to delete the current {{stateData}} dump and replace it with something a little easier to read:

<ul class="states">
   <li>
      <div class="resultwrapper">
         <span class="title">{{state.name}}</span><br>
         <span class="bold">Abbreviation:</span> {{state.abbreviation}}<br>
         <span class="bold">Capital:</span> {{state.capital}}
      </div>
   </li>
</ul>

Using ng-repeat and an unordered list, my state information now displays in a style-able list. Unfortunately, a couple of my states are not in alphabetical order. This can be fixed easily by telling the repeater to order it using a built-in filter module named orderBy after my iterator:

<ul class="states">
   <li ng-repeat="state in stateData | filter:criteria | orderBy:'name'">
       <div class="resultwrapper">
          <span class="title">{{state.name}}</span><br>
          <span class="bold">Abbreviation:</span> {{state.abbreviation}}<br>
          <span class="bold">Capital:</span> {{state.capital}}
       </div>
   </li>
</ul>

Note that ‘name’ is a string, not a reference. I could have also defined a property for it in the controller and used it with the orderBy.

Now that they’re in alphabetical order I want to be able to search them. This was done by adding a simple input and assigning it an ng-model of ‘critera’, then giving that to the ng-repeat filter. Angular uses the value entered into the criteria field as a filter for the stateData array. Throw in a style sheet and you have a pretty nifty widget using a very minimal amount of code.

The Result

Author: "rabidgadfly" Tags: "angularJS, factory, filter, module, serv..."
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 22 Jan 2013 15:17
This entry is part 6 of 9 in the series: AngularJS Learning Series

This AngularJS example demonstrates how HTML5 and AngularJS can work together to provide a modern approach to form submission and validation without lengthy JavaScript validation algorithms, cumbersome CSS, or page refreshes.

Note that there are multiple ways to present and submit a form using HTML5 and AngularJS. Your implementation should depend on the needs of your application. The method I use here does not perform an actual submit. Instead, when the Submit button is clicked it calls a function that updates a visitorInfo object. Any action can be performed when the visitorInfo object is updated by modifying the update function in VisitorFormController in app.js.

The example provides immediate feedback based on the data entered into the input fields. Every input field has been flagged as “required” and you can watch the debugging info to see the status change dynamically as each input field is populated.

[There is a JSFiddle embedded in this post. Please follow the link below or go to the site to see this JSFiddle.]

View this on JSFiddle

Let’s take a closer look at the email section to see how this is done:

<span class="label">Email:</span>
<input type="email" name="email" placeholder="Email" required="" />
<span class="valid">?</span>

The first line is simply the label that is show before the input field. The “label” class lets me apply some styling to keep it on the same line as the input field, make it bold, etc. No magic there.

The input field has several attributes. Name gives us a means of referring to that specific field. Type defaults to “text” but we’ve given it the HTML5 type of “email”. Doing so implements validation rules, such as requiring an & and a domain type (like .COM). It also causes responsive mobile devices to present different UI. For example, assigning a type of email will cause “.COM” to appear on keyboards of many mobile devices.

The ngModel directive links the input field to a scope property, in this case visitorInfo.email. visitorInfo is an object that holds all of the form properties. Notice that each input field model includes visitorInfo before the property name. You can watch visitorInfo populate in the debugging info as you fill in the form.

Placeholder is a new input attribute that allows you to define a short data entry hint that will appear inside the input field. The hint disappears when the user starts entering text but will reappear if the text is deleted. Placeholder text does not get submitted as form data.

Finally, there is the required attribute that defines the field as one that must be filled in for the form to be considered valid.

The span below the input field contains a checkmark that is not visible when the page first loads. The AngularJS ngShow directive has an evaluation in it that will only allow the span to be visible when the field passes email field passes validation rules.

Negative feedback is provided courtesy of CSS and AngularJS. Enter a value in the First Name field and then delete it. The field background will change to red. If you look in style.css you’ll see the following section:

input.ng-invalid.ng-dirty {
	background-color:red;
}

ng-invalid and ng-dirty automatically get assigned as classes based on the input field state. If the field contents are invalid then the input field will be dynamically assigned the ng-invalid class. We can use that class to style the field in certain circumstances as I did above. Pretty slick! See the AngularJS API for more information on these class assignments.

Finally, check out the Submit and Restore buttons. The Submit button’s job is to update the visitorInfo object. The restore button restores all of the field data to the last submitted value.

Both buttons react to the state of the form. The submit button will enable and turn green when the entire form has been filled out with valid information. The restore button enables when the form data differs from the stored visitorInfo object data.

This functionality is done using a combination of AngularJS’s ngClick and ngDisabled directives:

<button ng-click="reset()" ng-disabled="isUnchanged(visitorInfo)">RESTORE</button>
<button class="submitbtn" ng-click="update(visitorInfo)" ng-disabled="valForm.$invalid || isUnchanged(visitorInfo)">SUBMIT</button>

ngDisabled contains an evaluation. If the evaluation is true then ngDisabled will also be set to true, making the buttons un-clickable. If they evaluate to false then the buttons will become enabled. Once they are enable, they can be clicked and the clicks will be handled by the functions that are referenced in the ngClick directives.

All in all it was very easy. The code itself is MUCH shorter than this post, which is a testament to the simplicity of AngularJS and HTML5 (or it could be just an indication that I’m too wordy.) In either case, I’m using that line as an opportunity to wrap this post up.

As always, check out the code on Plunkr. Fork it, edit it, experiment with it. It’s the best way to learn.

Author: "rabidgadfly" Tags: "angularJS, form, html5, validation"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 08 Jan 2013 17:32
This entry is part 4 of 9 in the series: AngularJS Learning Series

My goal for this AngularJS experiment was to create a multi-level menu with a hide-away submenu, fed from an external data source. The sub-menu should appear when its parent is clicked. As with my other AngularJS examples, this turned out to be a very simple task involving minimal code.

[There is a JSFiddle embedded in this post. Please follow the link below or go to the site to see this JSFiddle.]

View this on JSFiddle

One directive in the example that I hadn’t used before was ngStyle which facilitates dynamic style assignment. I use it here to position the submenu under the appropriate parent item. The directive is assigned to the ul block, and when the parent item is clicked, a function is called that modifies the scoped ‘subLeft’ property, something like this:

<ul>
   <li ng-click="setStyle()">menu item</li>
</ul>
<ul ng-style="subLeft">
   <li>submenu item</li>
</ul>
$scope.setStyle = function() {
   $scope.subLeft = {'padding-left':'80px'};
}

One hurdle I had to overcome was that ng-click only takes an Angular expression, which does not use JavaScript eval() to evaluate. I wanted to send the id of the element that was clicked so I could derive its coordinates as a way of knowing where to place the submenu. Without the use of JavaScript I was unable to do that.

In the interest of keeping the example simple, I ended up sending the Angular iterator index instead of the element id. Since all of my menu items are the same width it was a matter of multiplying the index by that width to arrive at the correct positioning. Problem solved!

Author: "rabidgadfly" Tags: "angularJS, menu"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 03 Jan 2013 18:01

I made my first foray into XSLT territory recently. Quick definition from W3Schools:

“XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents. XSLT stands for XSL Transformations.”

Overall the experience was a good one. It was very easy to figure out how to display an XML document in an HTML report format. It was also very easy to style the report using attribute sets. Essentially, attribute sets allow you to define styles for different elements in your document. Elements use “use-attribute-sets” to define the sets that should be applied. For example:

<xsl:attribute-set name="bodystyle">
    <xsl:attribute name="bgcolor">
        #cccccc
    </xsl:attribute>
</xsl:attribute-set>

<xsl:template match="report">
    <html>
        <body xsl:use-attribute-sets="bodystyle">
            <xsl:apply-templates select="headerData"/>
            <xsl:apply-templates select="reportData"/>
        </body>
    </html>
</xsl:template>

The code above would make the body background color #cccccc. Works great. But what if I wanted to set a property that isn’t an attribute of the element. What if I want to set the font color, for example. There is no “color” attribute for body. In this case, the style attribute can be used:

<xsl:attribute-set name="defaultfontcolor">
    <xsl:attribute name="style">
        color:#111;
    </xsl:attribute>
</xsl:attribute-set>

<xsl:template match="report">
    <html>
        <body xsl:use-attribute-sets="defaultfontcolor">
            <xsl:apply-templates select="headerData"/>
            <xsl:apply-templates select="reportData"/>
        </body>
    </html>
</xsl:template>

So far, so good. The cool thing about attribute sets is that they can be combined, too. Let’s say I want to combine the two examples above and set the body color and font color at the same time. I could define both in the same attribute set, but I want to use the font color elsewhere without the bgcolor. This can be done easily:


<xsl:attribute-set name="bodystyle">
    <xsl:attribute name="bgcolor">
        #cccccc
    </xsl:attribute>
</xsl:attribute-set>

<xsl:attribute-set name="defaultfontcolor">
    <xsl:attribute name="style">
        color:#111;
    </xsl:attribute>
</xsl:attribute-set>

<xsl:template match="report">
    <html>
        <body xsl:use-attribute-sets="bodystyle defaultfontcolor">
            <xsl:apply-templates select="headerData"/>
            <xsl:apply-templates select="reportData"/>
        </body>
    </html>
</xsl:template>

As you can see in the body tag I’ve listed both attribute sets, separated by a space. This works great!

Now here’s the gotcha. The last attribute set in the list will override previous style definitions of the same attribute. Normally, this isn’t a problem…as long as you’re not using the style attribute in more than one set. While the style attribute can define more than one element property, “style” itself is the attribute. Therefore, if you try to combine two attribute sets that both define “style”, only the last one will be implemented, regardless of whether they define different properties.

For example, although the code below defines the same styles as the one above, only the defaultfontcolor attribute set will be implemented. This is because both sets define the same attribute: “style”.


<xsl:attribute-set name="bodystyle">
    <xsl:attribute name="style">
        background: #ccc;
    </xsl:attribute>
</xsl:attribute-set>

<xsl:attribute-set name="defaultfontcolor">
    <xsl:attribute name="style">
        color:#111;
    </xsl:attribute>
</xsl:attribute-set>

<xsl:template match="report">
    <html>
        <body xsl:use-attribute-sets="bodystyle defaultfontcolor">
            <xsl:apply-templates select="headerData"/>
            <xsl:apply-templates select="reportData"/>
        </body>
    </html>
</xsl:template>

It doesn’t matter that one defines background and the other defines color. It only matters that they both set the “style” attribute. And because defaultfontcolor is last in the use-attribute-sets list, its definition is used over bodystyle.

Author: "rabidgadfly" Tags: "XML, xslt, attribute-set, style, use-att..."
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 26 Dec 2012 17:48
This entry is part 4 of 9 in the series: AngularJS Learning Series

My goal with today’s AngularJS experiment is to load data from a JSON file, iterate through all the data, and dynamically display detail data from a clicked list item. This proved to be incredibly simple and ended up taking less than 50 lines of code, including comments!

The data loading is done using the AngularJS $http service. In this example, the data object is assigned to $scope.artists when it has been successfully loaded:

$http.get('artists.json').success(function(data) {
   $scope.artists = data;
});

Once the data is loaded I can iterate over it using the AngularJS ng-click directive. The code below loops over each record in the artists object that I loaded above. It displays the artistName property found in each artist and then assigned a function (setSelectedArtist) that will be executed when the name is clicked.

<ul>
	<li ng-repeat="artist in artists">
    	<a href ng-click='setSelectedArtist(artist)'>{{artist.artistName}}</a></li>
	</li>
</ul>

When an artist name is clicked, its artist object is passed to the setSelectedArtist function found in ArtistsController. setSelectedArtist assigns the artist to the scoped selectedArtist property. When that occurs, page references to selectedArtist are updated to reflect the new assignment:

<div class="detailimagewrapper">
    <img class="detailimage" src="{{selectedArtist.img}}" >
</div>
<p>{{selectedArtist.description}}</p>

Check out the example on Plunker. It’s well-commented and easy to modify. Try adding the artist’s genre to the detail section. Or add a new field, like recordLabel or dateFormed.

This post is barely the tip of the iceberg regarding what the AngularJS $http service offers. Check out the documentation to learn more.

Author: "rabidgadfly" Tags: "angularJS, http, json"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 18 Dec 2012 12:39
This entry is part 3 of 9 in the series: AngularJS Learning Series

This is the third in a series of posts detailing my experience learning AngularJS. This post and its accompanying example discusses the handling of scope. AngularJS scopes go hand and hand with the DOM (Document Object Model). DOM objects within a controller reference rely first on their controller counterparts for their property assignments.

The example below includes three controllers: Limericks, Limerick1 and Limerick2. Limerick1 and Limerick2 use identical property names, but each are given unique values. If you look at index.html you’ll see two DIVs with ng-controller references to their respective controller definitions in app.js. Because they’re separate DOM objects, they can use the same property names locally.

Try changing the “Title” and “Field” values within each of the limericks. Notice that only one limerick changes even though its property names are identical to the other limerick. (Sidenote: the example scrolls down quite a bit. To view it on a full page, open it up in plunker and click the eye icon on the right to view the rendered page)

[There is a JSFiddle embedded in this post. Please follow the link below or go to the site to see this JSFiddle.]

View this on JSFiddle

AngularJS controllers aren’t limited to local property definitions, though. They also inherit from parent scopes. Look at the DIV that references the Limericks controller. Notice that it wraps around both Limerick1 and Limerick2. This allows Limerick1/2 to inherit from Limericks.

To illustrate inheritance, {{author}} is defined only in Limericks but it’s used within all three controller objects. Try changing the value in the “Global Author” field to see how it changes in all three scopes.

But wait, there’s more! Inherited properties can be modified locally without affecting the parent value. Like {{authors}}, {{pageTitle}} is also only defined in the Limericks controller. Its value is “Pretty Bad Limericks”. The first instance of it on the page is outside of Limerick1 and Limerick2. The second instance is within Limerick1 and the third is within Limerick2.

Try changing the first instance by modifying the value in the “Parent pageTitle” field. Notice that both pageTitles change. Now try changing the value in the “Inherited pageTitle” field. Only the local value changes. Limericks1 {{pageTitle}} is now uncoupled from its parent value since it has been assigned a local one. If you change the first instance again you’ll notice that the Limerick2 instance is still inheriting but Limerick1 is not.

For more information on AngularJS scopes, see the dev documentation.

Author: "rabidgadfly" Tags: "angularJS, inheritance, scope"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 13 Dec 2012 19:17
This entry is part 2 of 9 in the series: AngularJS Learning Series

This is the second post of my learning experience with AngluarJS, Google’s HTML5/JS solution for building your own frameworks. In my first post I created an extremely simple app that added 2 values together. In this post I take that app a few steps further by creating a simple calculator.

This app demonstrates how to call scoped functions using button clicks, and how scoped variables can work together in an application.

[There is a JSFiddle embedded in this post. Please follow the link below or go to the site to see this JSFiddle.]

View this on JSFiddle

Admittedly, the ‘simple’ calculator ended up being a little trickier than I thought at first. There are several ‘gotchas’ that tripped me up along the way. Some examples:

  • There are special rules for the first number entered while the display output reads “0″. First, you don’t want to concatenate onto the 0. Second, if you enter a first number and then click the “add” button, no calculation should take place. This is especially important when subtracting where we would end up with -5 if “5 -” was entered. This is the reason the newNumber boolean variable is necessary.
  • When the “equals” button is clicked the first time it should add all of the number that have been inputted together. The second and subsequent times it is clicked (before any new values are entered) it should repeat the last calculation. For example, if “8 + 2 =” is entered, 10 will be the answer. If the equals button is immediately clicked again, it should add 2 to the result and output 12. It should continue adding 2 until a new value is inputted. This is the main reason for the pendingOperation and lastOperation variables.
  • The “add” and “subtract” buttons should only perform functionality when a value is pending. For example, “8 + 2 +++++++” should still result in a value of 10. This is unlike equals where the last action should be repeated (8 + 2 ===== equals 18).
  • The add button should subtract, and vice versa, when a previous subtract operation is active. In other words entering “8 + 2 -” should result in 10 being displayed in the output as soon as the subtract button is clicked.

So, the simple calculator ended up being more of a challenge than I expected. That being said, I built the app to learn about AngularJS and demonstrate its functionality, not to reconcile my checking account.

If you want to learn a little more about AngularJS, try modifying the Fiddle to add the ability to multiply and/or divide.

Author: "rabidgadfly" Tags: "angularJS, calculator"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 29 Nov 2012 15:09
This entry is part 1 of 9 in the series: AngularJS Learning Series

AngularJS Logo
Being a Flex developer who really loves his work, it still pisses me off that Adobe essentially buried Flash alive last year. That being said, when you make a living coding you have to keep up with the times. Enter AngularJS, Google’s js solution for building your own application framework. Extensible, dynamic, and pretty damned slick.

I haven’t hit the blog in a while so I figured I’d post some of my learning experience. ‘Hello Whatever’ is usually the first step in the learning experience, however the AngularJS team has a good example of this on their site. I’ll take it a quarter-step further in the hopes of providing something a little more unique.

I created a simple AngularJS app that will add two numbers together as they are changed. This demonstrates AngularJS’s binding between the form and the model. The AngularJS ‘Hello World’ example is actually included in the form of ‘Your opinion of angular’:

[There is a JSFiddle embedded in this post. Please follow the link below or go to the site to see this JSFiddle.]

View this on JSFiddle

Much of the magic is done with the ng-model directive which binds the view to the model using scope variables.

Author: "rabidgadfly" Tags: "angularJS"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 27 Jul 2012 18:15

DrupalEnabling Clean URLs in Drupal means getting rid of the URL parameters in your URL. Instead of http://www.mydrupalsite.com/?q=aboutpage the visitor will see http://www.mydrupalsite.com/aboutpage.

I’ve run into the Clean URL Test failure a few times now since I’ve been using Drupal (not long). Both times the solution has been the same (prompting me to blog the issue as a reminder).

Both times I’ve encountered the problem, it’s been while building a new site for a client on a temporary domain. When setting up hosting for a client I usually set up a new hosting account on a shared server and reference it by IP address until I’m ready to point the DNS servers at it.

The problem I run into is that, since the server is shared, a folder name is appended to the IP address, such as http://1.2.3.4/~mysite . That folder name is the reason that the Clean URL test fails.

If you install Drupal into a subfolder of your domain, you have to uncomment the RewriteBase line in your .htaccess file and change “/drupal” to your subfolder name. After doing so, your Clean URL test should pass.

Author: "rabidgadfly" Tags: "drupal"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 17 Oct 2011 15:59

I was notified on Friday that the entire web development team at my company, Pongo Resume, will be laid off at the end of this month. I’ve been a full-time web developer for 8 years. The majority of my time at Pongo was spent building their next-generation Resume Builder in Flex 4.5 as well as maintaining their legacy Resume Builder in Flash (AS2). I also spent a significant amount of time in ColdFusion 9 rewriting their billing process.

Before working at Pongo, I worked for 13 years at Hasbro where a significant amount of my time was spent building out their media portals using ColdFusion and Flash. The portals allowed viewing of videos, playing games, and reading online comic books. I also spent a good deal of time working with my friend and fellow blogger Dan Gaspar creating a ColdFusion/Model Glue API which provided access to our data to facilitate both internal and external development.

While my main focus has been within the Adobe stack; Flash, Flex, and ColdFusion, I also have experience in PHP, JQuery, JavaScript, and several other web technologies. I have worked with frameworks and I’m familiar with MVC concepts.

If you know of anyone in the Massachusetts or Rhode Island area that is looking for a developer please contact me or feel free to pass along my information. In addition to myself, there will be three other hard-working developers looking for work.

Thanks much!
Glenn Gervais

contact me

Author: "rabidgadfly" Tags: "Uncategorized, 01516"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 10 Mar 2011 18:37

Flash Builder makes it easy to generate getters and setters from a variable definition. Just select the variable, right-click and choose Source > Generate getters/setters.

The generated code is simple; the getter returns the value and the setter sets the value:

private var _myData:String;

public function get myData():String {
    return _myData;
}

public function set myData(value:String):void {
   _myData = value;
}

Oftentimes in Flex, however, changing a variable is a trigger that causes other code to run or update. But why would you want this extra processing to occur if the value that is being assigned hasn’t changed?

Instead, add a quick comparison:

public function set myData(value:String):void {
    if(_myData != value) {
       _myData = value;
    }
}

Note that you would use ObjectUtil.compare rather than equality to compare complex Objects:

public function set myObjectData(value:Object):void {
    if(ObjectUtil.compare(_myObjectData,value) != 0 ) {
       _myObjectData = value;
    }
}

Obviously, depending on the complexity and size of the objects, and the amount of work to be done after an update, comparing Objects may not make sense in all circumstances. That’s a judgement call you can make based on your particular code.

Author: "rabidgadfly" Tags: "as3, Flex, flash builder, getter, setter"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 28 Feb 2011 14:56

I’ve been implementing Swiz framework in my most recent Flex project. It’s worked great so far, but this one error sidetracked me for an hour or so:

"Could not get a reference to class for YourEvent.YOUR_EVENT_TYPE. Did you specify its package in SwizConfig::eventPackages?"


Obviously, the first thing to do when receiving this message is to make sure you specified the event package in SwizConfig::eventPackages. Once that’s confirmed, you ensure that the event has been imported, then try cleaning your project(s).

At this point it starts getting frustrating and you could easily start going off the rails moving code around and making crazy modifications. Before you get to that point, make sure you’re actually dispatching the event somewhere in your code. If you aren’t, then the event isn’t included when the application is compiled. Since it never gets included, Swiz cannot get a reference to it when the application runs.

This can happen when refactoring and moving events around a little at a time. If you’re like me, you do a little testing along the way to make sure everything continues to work properly. That’s when you can wind up in a case where you may be listening for an event that you haven’t yet written the dispatch code for.

It may seems like an occurrence that may happen once in a blue moon (Mmmm…Blue Moon), but it’s already happened to me twice in the span of a couple of weeks.

Author: "rabidgadfly" Tags: "Flex, swiz"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 26 Feb 2011 03:20

Here’s a quick tip on an issue that set me back a couple of hours. ORM stands for Object/Relational Mapping, an object-based method of reducing the amount of code required to communicate with a database. Hibernate is an ORM Framework included in ColdFusion 9.

I’m new to ORM so I started out by creating a simple project with all components contained under the same application. It was a small struggle to get past the new terminology and occasional mistakes and/or omissions in the online documentation, but a few hours and several expletives later, I was up and running.


My next step was to apply the method to an existing site. The major difference being that I wanted my ORM object definitions to be inaccessible externally. This required creating a ColdFusion mapping, which I created using the CF Administrator.

I set everything up and ran a test page which replied with an error: “Hibernate mapping for … component not found.”

After several hours of Googling, combined with a lot of trial and error, I discovered that in order to use Hibernate with a CF mapping, the mapping must application level. Once I deleted my mapping from CF Admin and added it to my Application.CFC, the error stopped and my results appeared.

One other note to keep in mind when configuring your ColdFusion application to use Hibernate: ORM settings must go in Application.CFC instead of the old-school Application.cfm.

-rG

Author: "rabidgadfly" Tags: "coldFusion, hibernate, orm"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 24 Feb 2011 18:46

I’ve been working with Flash Builder 4 every day for about six months now, and I love it. Overall, Flash Builder is a great programming environment offering helpful debugging tools, plenty of useful keyboard shortcuts, code-hinting and completion, and error feedback on compilation issues.

The compilation errors can be SO helpful that you rely on them as guides. When refactoring code the errors tell you where you need to go to fix affected code. And if you use metadata correctly, the errors can tell you when you’ve forgotten to include a required component.

As helpful as the metadata, code-hinting and error-checking is, it’s not quite perfect; and it’s these little imperfections that can set you off on an afternoon-long detour. Reason being, while metadata can help enforce rules and enhance code-hinting, and while error-checking can point out problems with your code, metadata itself is not error-checked.

Enter my problem…

I added a skin state and skin parts to an existing component and couldn’t for the life of me figure out why the component class would not update the content of the text fields I had placed in the skin. I’d done this several times before but this time it just wouldn’t work.

I made sure I had defined the skin parts in my component, I traced and debugged for several hours, I googled  and traversed several blogs, I read through the Adobe online help reading in-depth descriptions of getCurrentSkinState, invalidateSkinState, and attachSkin.

Finally, it dawned on me. I scrolled once again up to the section of my component where I defined the skin parts and looked closely at the meta data definition. Sure enough, there was the problem.  I had type “Skinpart” instead of “SkinPart”. I forgot to capitalize the P. No warnings, no errors; just a bunch of text fields in the skin and variables in the component that were acting appropriately on their own, but were not connected in any way.

It took about a half hour to remove all of the ridiculous code I had added to try to compensate for that lowercase p. In the end, I walk away with a better knowledge of Flex skins, and hopefully an ability to recognize that issue sooner in the future.

Author: "rabidgadfly" Tags: "as3, Flex, Uncategorized, actionscript, ..."
Comments Send by mail Print  Save  Delicious 
Date: Monday, 24 Jan 2011 14:34

Thanks for visiting the site. Unfortunately, the jackass that owned the server my site was hosted on decided to take it down without telling me. Luckily, I have a good portion of it backed up locally because I knew he was a jackass. I hope to be back up and running soon. Sorry for the inconvenience.

Author: "rabidgadfly" Tags: "Uncategorized"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 12 Nov 2010 02:33

Path is a Flex 4 drawing class that fills a shape using coordinates you provide. It’s very simple once you get the hang of it, and if you add some filters you can come up with a pretty nice looking image. In this post I’m going to show you a quick overview of how to draw a custom arrow using Path that can be used as a button as seen in this sample:


You can right-click the sample to view or download the source.

After creating a new Flex 4 Web Application project, I create a new MXML skin named NextButtonSkin based on spark.components.Button. While my button will use the states and functionality of a Spark button, it will use none of the look so I delete most of the default Button MXML. ( If you want more detail on button skinning you can take a look at my Create Your Own Image Buttons post. ) The remaining button skin code looks like this:

<?xml version="1.0" encoding="utf-8"?>

<s:SparkSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
			 xmlns:s="library://ns.adobe.com/flex/spark"
			 xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
			 minWidth="48" minHeight="48"
			 alpha.disabled="0.5">

	<!-- host component -->
	<fx:Metadata>
		<![CDATA[
		/* @copy spark.skins.spark.ApplicationSkin#hostComponent 	*/
		[HostComponent("spark.components.Button")]
		]]>
	</fx:Metadata>

	<!-- states -->
	<s:states>
		<s:State name="up" />
		<s:State name="over" />
		<s:State name="down" />
		<s:State name="disabled" />
	</s:states>

	<!--- Your arrow will start after this line --->

	<!---- Your arrow will end above this line ----->

</s:SparkSkin>

Notice that the code above doesn’t even contain a button because I’m going to create my own graphic to use as a button. To start, I add a Graphic containing a Path and a fill. I don’t draw my arrow first because, without a fill, I won’t be able to see the arrow I’m going to draw. At this point my Graphic code looks like this:

<!--- Your arrow will start after this line --->

<s:Graphic>
	<s:Path data="">
		<s:fill>
			<s:LinearGradient rotation="90">
				<s:GradientEntry color="0xfd1901" color.down="0xAF220D" />
				<s:GradientEntry color="0xa70d12" color.down="0xAF220D" />
			</s:LinearGradient>
		</s:fill>
	</s:Path>
</s:Graphic>

<!---- Your arrow will end above this line ----->

Now I can begin drawing my arrow. When creating a path, picture your image on grid paper. The lines you draw will run along the grid lines and the fill will color in the middle for you, something like this:

The arrow is defined inside the data property of the Graphic and each segment includes a segment type and x/y coordinates relative to the end point of the previous segment. I’m only going to use a few of the possible segment types, but if you want to see the full list you can check them out here.

Since I don’t have an end point when I start off, the first command I put in there, “m 5 20″, will tell the application that the segment I’m drawing will start 5 pixels in and 20 pixels down from the top of the Graphic area. If I were drawing the arrow on paper this would mean I was putting my pencil to paper 5 grid squares in and 20 down.

From there I want to draw a horizontal line 15 pixels long and extending to the right of my starting point. “h 15″ accomplishes the task. If I wanted the line to extend to the left, I would enter “h -15″. From that point I want to draw a line, slightly diagonal, that will be the beginning of the arrow head. There’s no “d” for diagonal, so I have to tell it to draw a line to a certain point. In this case, I enter “l -3 -8″ which draws a line from the end point of my horizontal line and extending 3 pixels to the left and 8 pixel up. Get the idea?

The finished arrow code looks like this:

<!--- Your arrow will start after this line --->

<s:Graphic>
	<s:Path data="m 5 20
			h 15
			l -3 -8
			l 18 14
			l -18 14
			l 3 -8
			h -18
			v -12">
		<s:fill>
			<s:LinearGradient rotation="90">
				<s:GradientEntry color="0xfd1901" color.down="0xAF220D" />
				<s:GradientEntry color="0xa70d12" color.down="0xAF220D" />
			</s:LinearGradient>
		</s:fill>
		<s:stroke>
			<s:SolidColorStroke color="0xAF220D" weight="1" alpha=".8" alpha.disabled="0"  alpha.up="0"/>
		</s:stroke>
	</s:Path>
</s:Graphic>

<!---- Your arrow will end above this line ----->

That’s it! My “Next” arrow is done. I follow the same process for the Previous button. Then, I add them to my default page, which ends up looking like this:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">

	<s:Button skinClass="PrevButtonSkin" buttonMode="true" left="25" top="25" />
	<s:Button skinClass="NextButtonSkin" buttonMode="true" left="100" top="25" />

</s:Application>
 

The skinClass attribute of the Buttons contains the name of the MXML skin files where I drew the buttons. That’s all there is to it.

To view or download the complete source, right-click on the app at the top of this post and click “View Source”.

-rG

Author: "rabidgadfly" Tags: "Flex"
Comments Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader