AngularJS

AngularJSX – AngularJS with JSX

I like Angular 1.X. It has allowed me to get some rich UIs done in a pretty short amount of time (unit tested, too!). However, with React gaining so much attention, I’ve been pretty jealous of JSX. One thing that’s always annoyed me about Angular is the jumping between multiple files for one page/component – the routing config, the controller, the template – and it can get jarring and cause me to lose focus. A solution? AngularJSX!

AngularJSX

“angular-jsx” is an plugin created by github user @thesam. It does what you’d expect – convert JSX in your JavaScript files to HTML strings. You can integrate this into your build procedures using “gulp-angular-jsx” or “grunt-angular-jsx”.

Gulp Build Example

var gulp = require('gulp');
var angularjsx = require('gulp-angular-jsx')

gulp.task('default', function () {
    return gulp.src('js/*.js')
        .pipe(angularjsx())
        .pipe(gulp.dest('outputdir'))
});

Grunt Build Example

module.exports = function(grunt) {

  grunt.initConfig({

    angular_jsx: {
      default: {
        files: [{
          src: ['src/*.js'],
          dest: 'build/'
        }]
      }
    }

  };

  grunt.loadNpmTasks('grunt-angular-jsx');

  grunt.registerTask('build', ['angular_jsx']);

};

Why?

Well, I like Angular and I like the idea of keeping the markup next to the controller code. It makes it easier for me read and manage. We COULD use string templates, but then you will lose all of your syntax highlighting and that’s not preferable. Here’s a screenshot of what using AngularJSX looks like:

2016-01-08_1034

Example of usage

Here’s a small example of how I have been using AngularJSX to keep my components in one file. This would be an Ionic view of a home controller.

var controllers = [];

// home.js example
controllers.push({
    name: "home"
    cache: false,
    url: "/home/",
    controller: function($scope, gameRoomClientService, $state, $log) {
        $scope.join = function() {
            $log.debug("Navigating to join page...");
            $state.go("join");
        };
        
        $scope.create = function() {
            $log.debug("Navigating to create page...");
            $state.go("create");
        };
    },
    template: (
        <ion-view title="Home">
            <ion-content>
                <button class="button button-positive" ng-click="join()">Join</button>
                <button class="button button-positive" ng-click="create()">Create</button>
            </ion-content>
        </ion-view>
    )
});

// app.js example
var app = angular.module("myApp", []);

app.config(["$stateProvider", function($stateProvider) {
    for (var i = 0; i < controllers.length; i++) {
        $stateProvider.state(controller.name, controller);
    };
}]);

Voilà!

What do you think? Like it? Hate it? Let me know on Twitter @kerryritter.

Leave a Reply

Your email address will not be published. Required fields are marked *