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']);

};

 

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);
    };
}]);