Blogs Hub

by AskGif | Mar 20, 2019 | Category :coding

AngularJS with JSX

AngularJS with JSX

<p>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&rsquo;ve been pretty jealous of JSX. One thing that&rsquo;s always annoyed me about Angular is the jumping between multiple files for one page/component &ndash; the routing config, the controller, the template &ndash; and it can get jarring and cause me to lose focus. A solution? AngularJSX!</p> <p>&nbsp;</p> <p>AngularJSX</p> <p>&ldquo;angular-jsx&rdquo; is an plugin created by github user @thesam. It does what you&rsquo;d expect &ndash; convert JSX in your JavaScript files to HTML strings. You can integrate this into your build procedures using &ldquo;gulp-angular-jsx&rdquo; or &ldquo;grunt-angular-jsx&rdquo;.</p> <p>&nbsp;</p> <p>Gulp Build Example</p> <pre class="language-javascript"><code>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')) });</code></pre> <p>&nbsp;</p> <p>Grunt Build Example</p> <pre class="language-javascript"><code>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']); };</code></pre> <p>&nbsp;</p> <p>Example of usage</p> <p>Here&rsquo;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.</p> <pre class="language-javascript"><code>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: ( &lt;ion-view title="Home"&gt; &lt;ion-content&gt; &lt;button class="button button-positive" ng-click="join()"&gt;Join&lt;/button&gt; &lt;button class="button button-positive" ng-click="create()"&gt;Create&lt;/button&gt; &lt;/ion-content&gt; &lt;/ion-view&gt; ) }); // app.js example var app = angular.module("myApp", []); app.config(["$stateProvider", function($stateProvider) { for (var i = 0; i &lt; controllers.length; i++) { $stateProvider.state(controller.name, controller); }; }]);</code></pre> <p>&nbsp;</p>

read more...