Skip to main content

Mobomo webinars-now on demand! | learn more.

 

snap 1

Modev started in 2008 as a Meetup group and over the years they have led the industry by organized conferences,strategic initiatives and provided executive leadership coaching to ensure those we engage with operate at peak performance.We were thrilled to have the opportunity to speak at the fifth annual Modev Conference on December 10th. Adam presented on the Ionic HTML5 hybrid mobile framework, where he talked about the framework’s background, as well as provided a quick dive into Angular.js, the popular javascript framework it’s built on.  

 

snap 4

Be sure to visit http://withinsight.github.io/modev-ionic/ to see the full presentation 

Categories
Author

ngCordova

I’ve previously written about the power of the Ionic CLI, which offers some great tools to developers building mobile apps using web technologies. While Ionic offers a CLI and mobile-optimized UI components, it doesn’t handle native level integration, for example accessing a user’s camera, or contacts. Since Ionic is built on top of AngularJS, we can use Angular to access native plugins, and this is where ngCordova comes in.

ngCordova is a framework that makes the native Cordova API available as AngularJS services. In this post, I’ll walk through setting up ngCordova, and accessing the contacts on a user’s device. First, a few prerequisites. You must have the following installed on your machine:

  • Git (If you want to follow along, or create your own repo)
  • NodeJS (Installing NodeJS installs its package manager, NPM)
  • Bower (You can use NPM to install both Bower and Ionic)
  • Ionic (The Ionic install instructions also have you install Cordova)

I’ve created a Git repository that you can checkout and follow along with, or you can create a new repo and progress through the steps on your own.

First, you’ll want to create a new Ionic app by running this command in Terminal:

ionic start ionic-ngcordova 

This starts a new Ionic project, in a folder titled “ionic-ngcordova”. That last bit is arbitrary; you can name it whatever you’d like. Also, this will by default use Ionic’s “tabs” app template (there are others, like “blank”, or “sidemenu” available).

Next, a few housecleaning items I tackle with any new Ionic project. In Terminal, change directories (cd ionic-ngcordova) so you’re in the folder Ionic just created, and enable Sass:

ionic setup sass 

Next we’re going to add a few directories to the Git ignore list that shouldn’t be included in our repo. To do this, open the project directory in your favorite text editor. For me, that’s Sublime, so I can open the current directory, with the folder structure visible using:

subl ./ 

With the project open in your text editor, locate the .gitignore file in the root directory. We’re going to add the following lines to the bottom of this file:

hooks/ www/css/ www/lib/ 

The hooks directory includes native Cordova JS that’s managed by Ionic, the www/css directory contains your compiled CSS (generated by Sass), and the www/lib directory is where Bower places all its assets (check out the .bowerrc file in the root directory for more info here).

With these steps complete, we have a nice clean repo, and you can run the app in a browser or the iOS Simulator via the command line to make sure everything is working:

// Browser  ionic serve  // OS Simulator  ionic emulate ios 

Now for the fun stuff. Back in Terminal, in the project root, let’s install ngCordova:

bower install ngCordova --save-dev 

This installs the ngCordova package (specifically, in www/lib/ngCordova), and saves it as a dependency in the bower.json file in the app root (The --save-dev flag, a good habit to get into).

Back in your text editor, open up the index.html file, located at www/index.html. This is the root HTML file that your app runs on. Now that Bower has placed the ngCordova library in www/lib/ngCordova, we need to reference ngCordova’s JavaScript file in our app’s index.html file. Include this line after the line that includes the bundled Ionic/AngularJS file:

<script src="lib/ngCordova/dist/ng-cordova.js"></script> 

Next, we need to inject ngCordova as a dependency into our AngularJS app. This is done in the app’s primary JS file, located at www/js/app.js. Following the other default controllers and services injected by Ionic, add ‘ngCordova’:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova']) 

ngCordova is now available to our app, and we can install and start using any of the native Cordova plugins listed in the ngCordova docs. Let’s see how we’d access the user’s contacts using the $cordovaContacts plugin.

First, we need to install the plugin using Ionic:

ionic plugin add cordova-plugin-contacts 

This installs the Cordova Contacts plugin in the plugins directory in the app root. The ‘ionic plugin add’ command is essentially the same as Cordova’s ‘cordova plugin add’. Check out the Cordova docs for more info here.

Now that we have our native plugin installed, let’s emulate using the iOS Simulator, also using the livereload feature of Ionic’s CLI:

ionic emulate ios -l 

This will launch the app in the iOS Simulator, and reload in real time as you make code changes in your text editor.

With the app running in the iOS Simulator, we’re only a few steps away from accessing the user’s contacts. First, we need to inject the $cordovaContacts service into the controller where we want to access the contacts from. I think a user would probably access contacts from their Account tab, so let’s open up www/js/controllers.js, and inject $cordovaContacts into the Account controller:

.controller('AccountCtrl', function($scope, $cordovaContacts) { 

With the service available to our controller, we’ll add two buttons that will allow the user to select a single contact, or multiple contacts, respectively. Open up www/templates/tab-account.html, and add this markup following the closing tag. This will use the standard Ionic button markup:

<button class="button button-positive button-block">   Get Contact </button>  <button class="button button-positive button-block">   Get Contacts </button> 

Now for the magic. Our last step is setting up a function to be called when the user touches a button, and calling the $cordovaContacts appropriately based on which button they’ve touched.

First, let’s add the click handlers using Angular’s ng-click directive:

<button class="button button-positive button-block" ng-click="getContact()">   Get Contact </button>  <button class="button button-positive button-block" ng-click="getContacts()">   Get Contacts </button> 

At this point, your app should look like this:

ios button

Lastly, let’s create the functions in www/js/controllers.js. In the AccountCtrl controller, add the following lines after the $scope.settings object:

$scope.getContact = function() {     $cordovaContacts.pickContact().then(function(result) {         console.log(result);     }); }  $scope.getContacts = function() {     $cordovaContacts.find({multiple: true}).then(function(result) {         console.log(result);     }); } 

If you hit ‘c’ in Terminal, this will enable Ionic’s console logs feature, and you’ll see the contact objects being logged as you touch the buttons. Alternatively, you can launch Safari, then go to Develop > iOS Simulator and visit the full Safari console there.

You’ll notice that touching the “Get Contact” button launches the native iOS contact picker component:

contact picker

The “Get Contacts” button simply grabs all the contacts on the device and dumps them to the console, in all their gory detail. Creepy:

console

While ngCordova is the bridge that allows easy access to Cordova plugins via AngularJS, all the Cordova plugins available have more documentation than is found on the ngCordova site. You’ll notice an “Official Docs” link on each ngCordova docs detail page, which points to the original Apache/Cordova documentation, for example the official Cordova Contacts documentation.

Hopefully you can see how in just a few steps, we’re able to setup a new mobile app using Cordova, leverage Ionic’s tools and UI components, and further layer in ngCordova to access Cordova plugins via AngularJS.


Any questions, thoughts, ideas? Let us know!

Want to learn more? Check out Intridea's posts on Ionic CLI and Ionic Experiments

Categories
Author

ionic

There’s been a lot of buzz around Google’s Material Design recently, from Material Design Lite (Google’s non-JS implementation of Material Design), to Angular Material (Google’s Angular port of the Material Design library), to Ionic Material (a non-Google project that builds on top of Ionic’s UI), and even Google’s Material Design implementation with Polymer’s Paper Elements.

Envisioning a scenario where a client has heard of Google’s Material Design, and requests it as the UI basis for a mobile project, I set out to see what would happen when we start to implement some of these new front-end options in an Ionic/Cordova app.

Angular Material

Angular Material is an implementation of Material Design in AngularJS, that’s supported internally by Google. It provides UI components from the Material Design library as easy-to-implement AngularJS directives, and has a strong focus on accessibility, which is a big concern with AngularJS apps.

The demos for Angular Material are very well fleshed out, and it looks promising. I was able to integrate into Ionic easily, as both run on AngularJS. I spent almost zero time on CSS, but I was able to achieve comparable results.

Here’s what the Angular Material md-card directive looks like (Ionic on the left, Angular Material on the right):

angular

Here’s what it looks like when you swap out the Ionic list directive with the Angular Material list directive:

angular

I’ve created a demo repo if you’d like to see the changes I made, and download, run and play with the implementation yourself.

Ionic Material

Ionic Material is not maintained by Google, but has some pretty slick demos. It’s designed to be layered on top of Ionic, and enhance the existing directives, meaning it’s even less of a switch than implementing Angular Material.

Upon setting it up in the app, I didn’t really have to change much other than adding Ionic Material to the project, and already the “material” design impact is felt:

ionic

I’ve also created a repo showing the implementation of Ionic Material in an Ionic app.

Polymer

Is implementing Polymer in an Ionic app a good idea? Who knows. Probably not. I wanted to see how far I would get before running into issues.

Implementing Polymer in Ionic was fun, and the bonus here is that you’re using web components which are on track to be standardized in browsers, so you have to love the compatibility forecast. I was able to replace Ionic’s header with Polymer’s paper toolbar, I added Polymer’s iron-pages and paper-tabs in place of Ionic’s tabs, and converted the layout to use the paper-scroll-header-panel web component.

This screenshot is taken as the touch animation is firing on one of the tabs:

polymer

I’ve created a repo for the Ionic Polymer experiment, so you can check out how that looks locally.

Summary

Angular Material is currently at 0.10.0, so I ran into components that didn’t work pretty quickly. That FAB Speed Dial component sure does look snazzy, though. It’s an internal Google project, so I expect we’ll see a lot coming soon. Since it’s so early in the development, I’m going to put this one on my watch list and kick the tires again once a bit of time has passed.

Ionic Material is even earlier in its development, currently at a 0.0.1 release. It will probably be the easiest to implement, once its ready. While not an official Google project, this is also one to put on your watch list.

Polymer starts to clash with AngularJS pretty quickly. For example, I ran into issues with data binding, and I really was just scratching the surface. It’s probably best to implement Polymer as a Cordova app, without Ionic, so you avoid these conflicts. Of course, you also lose a lot of value if you remove Ionic from the equation, so there’s room for discussion, depending on the project.

Hopefully this has given you some insight into the recent developments surrounding Google’s Material Design library, and how they might fit into your Ionic mobile app development cycles.


Any questions, thoughts, ideas? Let us know!

Want to learn more? Check out Intridea's post on Ionic CLI.

Categories
Author

angularjs lock

What is Async?

Async (aka asynchronous) JavaScript refers to the execution of more than one piece of code at the same time. This is great because it prevents your application from freezing up when certain code takes a long time to execute, but it can also cause issues in your code if you are expecting something to be complete when it may not be. These situations are called race conditions. Here is an example of when a function is performing asyc code and we don’t get the result we are expecting:

. Notice the name variable isn’t returned as “Bob”, but is instead returned as it’s initial value.

Enter: Promises

Promises allow developers to detect when asynchronous code finishes and then act on it. Instead of a function returning a value we expect, we can have it return a Promise, and then let the Promise tell us when the value is ready to use. Now let’s take a look at how Promises can fix our issue in the original example:

. Using the built-in promise library $q that ships with Angular, we can return a Promise instead of just the name variable. The Promise is “resolved” after the timeout finishes, which tells the promise to execute its then method to finally return the value we originally wanted.

Real-world GitHub API Example

One of the most common uses for Promises is within a Service that makes a HTTP call and returns the response to a controller. Since HTTP calls take some time to finish, they are a prime candidate for Promises. Here’s an example of how we can use a Promise to return the HTTP response to a controller when it’s ready:

Advanced Promises

Let’s say you need to make a number of consecutive HTTP calls within your Service before returning the result back to the controller. The $q library has a very useful method call $q.all. This allows you to pass an array of Promises to the method and it will only execute its ‘then’ method once all Promises have been resolved. This prevents any race conditions when executing multiple HTTP calls before performing another action.

Another case where we can use multiple Promises is a technique called ‘Chaining Promises’. Sometimes within a controller, we’ll need to call one HTTP Service before another HTTP Service can be called, in case we need information from the first Service. The nice thing about $q Promises is that the Promise itself returns a Promise. This way we can have a function return one of our Services that returns a Promise and then act on that once it’s ready. If we take our GitHub API example, I can chain the ‘getGithubUserInfo’ function with another function by returning a Promise. This is what that might look like:

Conclusion

Promises are a powerful tool in software development. Any web developer should have at least a basic understanding of Promises, if not a thorough grasp of the concepts discussed in this article. Please feel free to fork and edit these codepen examples to test our your own skills with Promises so you can master this critical technique.

Categories
Author

Ionic
With the release of Ionic 1.0, we’ve reached a new level in building hybrid mobile applications via web technologies. While Ionic is probably more well known for its CSS components and JavaScript/AngularJS extensions, I’d like to highlight a few tools that have really improved my ability to develop applications rapidly, which are included with the Ionic CLI.

The first, and probably most time-saving tool in the Ionic CLI, is the ability to live reload your app as you make code changes. Prior to being able to live reload, if you wanted to preview/test changes in a simulator or on an actual device, you would have to “build” (or compile) your app’s package, and then “run” (or install on the device, and launch). Web developers familiar with using live reload in Chrome to debug web apps will be very familiar with the Ionic CLI live reload process. Each time you save an HTML, CSS, or JS file that’s being “watched” in your app, the app will refresh while running on your device, so you don’t have to build & run each time (which is a very slow process). You can also change the files being watched by editing the watchPatterns in your ionic.project file. Read more about the live reload tool on the Ionic blog, or in the CLI documentation.

One of the great features of developing hybrid apps is leveraging the same code base for building iOS and Android apps. Ionic’s CSS components and JS extensions appear differently on iOS and Android, as they’re geared to mimic each native platform closely. The Ionic Lab tool allows developers to launch a browser window displaying how the app would look and behave on both iOS and Android. Since its running in a browser, it’s not going to allow you to preview native-level functionality, like if the ngCordova $cordovaCamera service performs differently on each platform, but it is very handy for monitoring CSS changes, and whether a change you made breaks something on one platform, but not the other. It also comes with the aforementioned live reload tool built in, so you’ll see both the iOS and Android version of your app refreshing in real time. Read more about Ionic Lab on the Ionic blog, or in the CLI documentation.

The last tool I really appreciate is the ability to print your app’s console logs to the Terminal tab you’re running the app from. There was a time when, before Safari allowed debugging of an iPhone connected to a Mac, developers had to hack together a solution in order to gain visibility into the JS running in their hybrid app running on a device. This consisted of Xcode logs and a tool called WEINRE (“WEb INspector REmote”). It was not pretty. Suffice to say that the ability to access the console logs of your app running on a device by simply passing the “-c” flag when running the “ionic serve” command is nothing short of a godsend. Read more about the command line flags available with the Ionic CLI.

While using live reload, Ionic Lab, and a combination of console logs and other tools available with the Ionic CLI have vastly improved the speed with which I can build hybrid mobile apps, the Ionic CLI currently has many additional features. You can emulate or run your app on a simulator or actual device, automatically generate the icons and splash screens required for both iOS and Android, or share your app with others using Ionic View. There are also many more exciting things in the pipeline, like Ionic Deploy (update your app without having to resubmit to app stores), Ionic Analytics (track all activity in your app), and Ionic Creator (prototype Ionic apps using drag-and-drop components).

Its an exciting time to be a hybrid mobile app developer, and Ionic is leading the pack when it comes to modern hybrid frameworks. Start building your own apps today!

Categories
Author

Have you ever been working with a particularly complicated web application and found that the output you were getting back from $log was difficult to wade through? Perhaps it's a complex XML response (because you're working with a SOAP API), or it's a particularly dense JSON response. Maybe the browser you use as your primary workhorse is working fine, but you found a gnarly bug in handling the response you're getting back from an API and it's failing in one of the other browsers you’re testing?

I recently ran into an issue similar to this; for me, it was while working with a SOAP API. And while the browser I'm using has all of the necessary development tools, emitting the responses I was looking for in an easy-to-read way was just not happening for me. No matter how I went about logging it all out, the response was coming back as a single line of text when emitted to the JavaScript console, and because it was a string I was having trouble easily inspecting it. While I wasn't having browser-specific issues (in this case), needing to add the extra effort of moving over to a view in my debugger was costing me precious turn-around time in trying to debug this response. If I was having this sort of issue with these responses, then the other developers on my team likely were as well.

After doing some research, I came across a fairly light-weight library called vkbeautify, which handles beautifying (as well as minifying) strings that are passed in to the appropriate method. This solved part of my problem: I now had a way to programmatically re-format my XML strings. Now, I could have stopped with simply injecting the library into the application, then just emitting out the formatted strings while I was debugging the issue I was trying to resolve. However, as I mentioned earlier, I'm working as part of a larger team, and I wanted the rest of the team to have this ability as well. Furthermore, I wanted us to be able to selectively emit data into the console in a consistent manner with some sane defaults.

The next logical step was to look at the $log service. Since this is an abstraction of the global console interface (log, info, warn, debug, etc) and it had the benefit of being stubbed so it wouldn’t display in unit tests, it made sense that I should simply extend that service. That way, any developer could call a method of the $log service to emit these nicely formatted strings.

To accomplish this, I created a provider decorator for $log and made it available from within the application. One of the nice things about provider decorators is that you can leverage a reference parent service and then call that service’s methods, which was nice because I wanted to leverage the existing infrastructure as much as possible – truly extending the $log service. So, I added a new method (called pretty, a nod to the concept of "pretty printing," which is common in most programming languages), and had that piggy-back on one of the other methods in the service. It looks a bit like this:

angular.module("myApp").config(["$provide", function ($provide) {   $provide.decorator("$log", ["$delegate", function ($delegate) { // $delegate, here, is an internal       reference to $log     $delegate.pretty = function (input, opts) {       var output;       opts = opts || {};       output = vkbeautify[(opts.type || "json")]](input); // use the correct vkbeautify for beautifying the        string - vkbeautify.json, vkbeautify.xml, vkbeautify.sql, etc; defaults to json       $delegate[(opts.output || "log")].call(null, output); // leverage one of the other $log methods to    actually emit the output; defaults to log     };     return $delegate;   }]); }]); 

Now, in our application, when a developer makes a call to $log.pretty(), the input they pass to it is run through vkbeautify with the given data type and output method (defaulting to json and $log.log, respectively). These values can be changed by passing in an Object as the second parameter with a property of type or output set to the desired value. Here are a few examples:

$log.pretty("<div><h1>Hello world</h1></div>", {type: “xml”); // // <div> //   <h1>Hello world</h1> // </div>  $log.pretty("body:{background:#fff;}.rounded_box:{border-radius:20px;}", {type: "css"}); // // body: { //   background: #fff; // } // .rounded_box { //   border-radius: 20px; // }  $log.pretty({jsonObj: {childAry: [1,2,3], childObj: {someProp: "prop"}}}, {output: "info"}); // this would    emit using $log.info; leveraging that type is defaulted to json // // { //   jsonObj: { //     childAry: [ //       1, //       2, //       3, //     ], //     childObj: { //       someProp: "prop" //     } //   } // } 

While I lose the ability to log out multiple items with this method (console.log(var1, var2, var3), for example), I gain the far more important ability to emit nicely formatted output that is easier to scan and understand. The big take-away here is that you can leverage the ability to extend $log to create output necessary to make debugging your code simpler. Think of the existing API as a starting point, and go from there. Chances are good that most use cases are already covered, but there's always something that isn't.

Finally, to help anyone else that finds themselves in this specific situation, I’ve released this as a package that’s available on bower. Just run bower install ng-log-pretty and include both vkbeautify and the library itself in your application and you’ll be off and running. You can also check out the code on GitHub.

Categories
Author

shink
If you’re reasonably up-to-date with front-end app development then there’s a good chance you’ve heard the buzz flying around about ECMAScript 6. For those unfamiliar, ECMAScript 6, also known as Harmony, is the next major version of JavaScript programming language. In this post, I’ll utilize new ECMAScript 6 features to reduce and improve readability of code in a sample AngularJS application.

Our sample application is a simple baseball card auction app that serves as a platform for users to sell rather valuable baseball cards and consists of three Controllers (BaseballCardsCtrl, BaseModalCtrl, and ConfirmModalCtrl) and three Services (UserService, CardService, and NotificationService).

Block-scoped bindings and arrow functions

The very first thing our application needs to do is fetch the current user’s profile, so we’ll start by taking a look at the getUserInfo function of our UserService which is responsible for retrieving the user’s information.

function getUserInfo() {     if (user) {         return $q.when(user);     } else {         let handleSuccess = (response) => {             user = response.data;              return user;         };          let handleError = (error) => {             NotificationService.logError('Unable to retrieve user info', error);              return null;         };          return $http.get('/dist/data/get_user_info_response.json').then(handleSuccess, handleError);     } } 

This function uses two of the new features of ECMAScript 6, namely block-scoped bindings, and arrow, or lambda functions. The handleSuccess and handleError functions above are declared using the let keyword, which restricts them to only being accessible by code in the same block; in this case, the else block of our if-else statement. This increases the overall readability of our code by moving variable or function declarations and assignments into the block where they’re intended to be used. Both handlers make use of arrow functions which provide a shorthand, expressive syntax for defining functions. In addition to providing a more compact syntax for defining functions, arrow functions also lexically bind the “this” keyword value, eliminating the need to manually bind object context when registering event handlers and such.

Generators and paused execution

Next, let’s take a look at an excerpt from our BaseballCardsCtrl that uses the UserService’s getUserInfo and CardService’s getCards methods to retrieve and store a reference to the user’s profile and baseball card data.

var it;  initialize();  function initialize() {     vm.notifications = NotificationService.getNotifications();      it = fetchData();      it.next(); }  function *fetchData() {     vm.user = yield getUserInfo();      vm.cards = yield getCards(vm.user); }  function getUserInfo() {     UserService.getUserInfo().then((user) => { it.next(user); }); }  function getCards(user) {     CardService.getCards(user).then((cards) => { it.next(cards); }); } 

The most interesting thing to note about the above code is the *fetchData function declaration. The function name is prefixed with an asterisk which is a new, special naming convention that results in the function returning a Generator object, another new feature of ECMAScript 6.

Generators are special Iterators that can pause their execution when the yield keyword is encountered. The ability to pause function execution allows us to control the order of asynchronous operations without need to use a series of nested callbacks. In our initialize function above, we store a reference to the Generator object on which we immediately invoke it’s next method to instruct *fetchData to begin executing its function body. The *fetchData function calls getUserInfo then pauses due to the presence of the yield keyword. The getUserInfo function is responsible for registering a callback function to be executed once the user’s information is retrieved from the server. Once the user’s information is retrieved, the callback invokes the Generator’s next function with the user data, which is returned by the first yield statement in *fetchData. The *fetchData function then releases the pause allowing execution to continue and the getCards function to be invoked with the necessary user data.

Object destructuring and string templates

Now that our application has been wired up to retrieve the necessary user and baseball card data, it needs a way to allow our user to actually sell his cards. The following snippet is from our CardService.

function sellCard(card, index) {     return $http.get('/dist/data/sell_card_response.json').then(handleSuccess, handleError);      function handleError(error) {         NotificationService.logError('Unable to sell card', error);          return null;     }      function handleSuccess() {         var { year, firstName, lastName, value } = card,             dollars = $filter('currency')(value);          cards.splice(index, 1);          UserService.updateBalance(value);          NotificationService.logSuccess(`Sold ${year} ${firstName} ${lastName} for ${dollars}`);          return card;     } } 

The majority of this code looks similar to what you’ve seen in other AngularJS applications with one exception, the first line within the nested handleSuccess method. This particular line uses what’s called Object Destructuring, another one of our new ECMAScript 6 features. Object Destructuring provides a shorthand syntax for declaring one or more variables with their values being initialized as property values of a target object. This is only a very basic example of how one might use Object Destructuring to consolidate multiple variable declarations into a single statement; it does support more complex mappings to nested object properties as well.

Another difference you may have noticed is our use of a string template to build a success message to be used as a “successful sale” notification. Traditionally, this would have been accomplished by concatenating multiple string literals with variables, but now we can achieve the same result using much more concise, readable syntax using variable interpolation with template strings.

Classes and prototypal inheritance

One requirement of our application is to prompt our users to confirm that they would like to proceed, after clicking a button to sell a particular baseball card. For this demo we use the UI-Bootstrap modal for our confirmation prompt. In real world applications there is often the need to utilize many different modals that implement a common subset of functions to handle repetitive tasks such as closing the modal when the user clicks a Cancel button. Implementing these functions for each modal leads to redundant code. Fortunately, ECMAScript 6 introduces a new way to approach prototypal inheritance in JavaScript using a more concise, readable syntax.

function BaseModalCtrl($modalInstance) {     'use strict';      var vm = this;      vm.dismiss = $modalInstance.dismiss;     vm.close = $modalInstance.close; } 

First we define an ordinary constructor function that creates dismiss and close members that reference the $modalInstance service’s dismiss and close methods. Admittedly, there’s nothing new or interesting to see here but in our next code excerpt, we will see how we can easily extend this functionality when we create our ConfirmModalCtrl.

class ConfirmModalCtrl extends BaseModalCtrl {     constructor(data, $modalInstance) {         super($modalInstance);          this.data = data;     } } 

While this feature isn't a new concept in JavaScript language, it does provide syntactic sugar, and achieve prototypal inheritance using a more concise, intuitive syntax. ECMAScript 6 classes and inheritance offer a standardized way to define JavaScript class constructors, public and private members, and make superclass methods calls. Of course, this is all possible today using native ECMAScript 5 code, but the syntax is not as elegant or intuitive. We now have an easy, readable way to extend functionality and eliminate code redundancy in our JavaScript classes.

Structure through modules

Lastly, let’s learn how to import various application components and register them with AngularJS. Historically, JavaScript has lacked a native way to structure applications and manage component dependencies. However while AngularJS does have its own dependency injection mechanism, it does not support importing external dependencies and requires components be available from within the current scope before registering with Angular.

ECMAScript aims to provide a native, standardized way to handle importing external dependencies with the introduction of modules. Lets take a look at how we can utilize the new module syntax to import external file dependencies and register our different components with Angular.

 import BaseballCardsCtrl from './controllers/baseball_cards.ctrl.js';      import ConfirmModalCtrl from './controllers/confirm_modal.ctrl.js';      import UserService from './services/user.service.js';      import CardService from './services/card.service.js';      import NotificationService from './services/notification.service.js';   angular.module('demo', ['ui.bootstrap'])   .controller('ConfirmModalCtrl', ConfirmModalCtrl)   .controller('BaseballCardsCtrl', BaseballCardsCtrl)   .service('UserService', UserService)   .service('CardService', CardService)   .service('NotificationService', NotificationService); 

As you can see in our above example, ECMAScript 6 modules introduce the new import keyword, allowing you to reference application components defined in external files. Here, we import each of our AngularJS application components (BaseballCardsCtrl, ConfirmModalCtrl, UserService, CardService, and NotificationService) and register them with our demo application. Each of our components uses an export statement, another new keyword in ECMAScript 6, to selectively make internal components available for import and use in other files..

 export default NotificationService;    function NotificationService($log, $timeout) {   ...   } 

The import and export statements support different syntax giving you flexibility over how components are referenced throughout your application. Note: We’ve only used the most basic, as it fulfills our application’s current needs.

Conclusion

ECMAScript 6 is still in draft mode and its specification isn’t expected to be officially published until later this year. For this reason, modern browsers currently have varying or incomplete support for many of the new language features. Fortunately though, there are quite a few tools to integrate support for ECMAScript 6 into your workflows and translate the code to ECMAScript 5 compatible syntax. As the release of the new ECMAScript 6 specification approaches, its new features are being integrated into more and more applications.

JavaScript is one of the most popular and widely used programming languages today; it’s not going anywhere any time soon and as it continues to evolve, so should our applications to harness it’s full potential and expressiveness. Our sample application uses one subset of the new features available in ECMAScript 6; there’s a lot more to it than what we’ve seen in this short example. For more complete information on ECMAScript 6 and how to integrate support for it in your workflow, check out the following resources.

Application

 

 

Resources

 

 

Categories
Author

working from home
Working remote is great; autonomy, flexibility, work/life balance, you name it! However, while the benefits severely outweigh the costs, working from home does present its own set of challenges. Below are the findings of a veteran to remote working.

1. You get to work from home, but you shouldn’t always.

Working remote is the freedom to work from anywhere. Often times we get fixated on remote equaling home office, but it so much more than that! Perhaps you enjoy working out in the sun, or maybe a little structure at a co-working space is your thing? Whatever it is - the point is you get to choose and that’s a beautiful thing.

Some of my best connections, ideas, and productivity have occurred outside the home office, so just because you can work from your kitchen, doesn’t mean you always should.

2. Autonomy is amazing, but also requires intentional discipline.

When describing my job, I often equate it to being your own boss w/o the usual entrepreneurial stressors. However, while there’s tons of freedom, with that freedom comes great responsibility (Spiderman plug). Sticking to a schedule, writing out your daily goals, and keeping yourself motivated are crucial to a healthy and effective work life. If you’re someone who thrives under constant supervision, be wary of remote jobs, this may not be for you. Self motivation and discipline are key to success in this arena.

3. Effective communication is a requirement, not a nice to have.

With the subtraction of body language, tone of voice, and physical proximity, the written word, emoticons, and timely responses become crucial. This is why utilizing GIFs, emoticons, and #status updates are important. If you think you’re being redundant, you’re probably doing just the right amount. Never underestimate the importance of emotional intelligence in the virtual world.
Think you can hack it? Intridea is hiring! :) Learn more about our AngularJS Engineer position.

Categories
Author

AngularJS editor

When it comes to learning your editor, most of us avoid it like the plague. It’s time consuming, opinions run rampant, and quite frankly, we’ve got better things to do!

Yet this avoidance isn't effective (and we know it). Simple tasks such as performing “find and replace” become much more difficult when we don't understand how our editor operates...

So why do we still refuse to eat our vegetables? For a few reasons:

It’s overwhelming.

Reviewing an editor, like emacs (or vim, or sublime text) is overwhelming. Not only can the editor accomplish many tasks, but there are multiple ways of doing them! For instance, when performing a “find and replace” on a file in emacs, you can use a regular expression (now you have two problems) or a keyboard macro. All these options can quickly lead you down a rabbit hole and wondering (three hours later) “what did I just do with my time?!”

Getting sidetracked by editor holy wars

When asking a co-worker for advice, if that co-worker doesn't use your editor of choice the discussion can devolve into: "Emacs is awful. You should use Vim and do it this way." Then instead of learning your editor, the conversation continues into the merits of one editor versus another, when both could do the job adequately. Avoid this at all costs.

Deadlines

We have work to do. When working on a bugfix or a feature with a tight deadline, you can't afford to spend time learning your editor. But then, not learning your editor makes your text editing less efficient, which makes development work take longer than it should. Soooo...

A Better Approach

Despite all these variables though, learning your editor is worth it. You just have to get strategic. Here’s my suggestion: while doing your everyday work, keep a notepad with an ongoing “need to learn” list for your editor. Then, when you find yourself wanting to perform a particular task (search across project files) and don't know how to do it, you can come back to it later vs. stopping everything to figure it out right then and there.

Then once a week, for thirty minutes, take one item on your list and look up how do it. For the coming week, keep in your mind (or a post-it note on your monitor) how to perform this task in your editor, and use it when necessary. This will help you remember the task and how to do it. Next week, you can cross off another item on your list.

This approach requires a small time commitment each week and avoids going down the rabbit hole of configuring your editor during your normal work day.

Categories
Author

angular

This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!

If you follow the front-end world even a little bit, you've probably seen the internet explode over the massively incompatible rewrite that is AngularJS 2.0. Some think the Angular team has lost their marbles. I'm not so sure.

Angular is dominating the story for modern front-end frameworks right now. Even if it's not your personal favorite, you have to admire its meteoric rise. It's a rare case of a library achieving massive adoption from both the startup and enterprise set in a very short timeframe (it took Rails years to get buy-in from bigger businesses). The Angular team is sitting on top of the world, and what do they decide to do? Rewrite the whole thing from scratch.

Advice Dog

Are. They. Insane? Rewrites-as-new-versions have horror stories right out in the open! Python 3.0 was released nearly six years ago and still has a puny fraction of code being written for it. Enterprise developers have only just convinced their bosses to let them build with modern web tech, and now they have to sell them on either a massive rewrite of existing code or an 18-month support death clock. The hubris of the Angular team is unmatched since the times of Marie Antoinette!

Disapproving Zoidberg

Except, that's not what's really going on. The Angular team isn't squandering their community goodwill out of sheer capriciousness. Instead they're doing something risky: they're pro-actively disrupting their own product before it's rendered irrelevant by external competition.

But Michael, I hear you thinking, you just talked about how dominant AngularJS is. Shouldn't they be taking steps to reinforce their leading position rather than putting the whole project in jeopardy?

That's certainly an approach they could take, but I believe it would ultimately lead to Angular falling by the wayside two to three years from now.

The Innovator's Dilemma

An oft-referenced issue in the tech world is the Innovator's Dilemma, as described in a 1997 book by Clayton Christensen. Wikipedia summarizes it thusly: "successful companies can put too much emphasis on customers' current needs, and fail to adopt new technology or business models that will meet customers' unstated or future needs...such companies will eventually fall behind."

I'll admit that I hadn't been following the progress of the Angular 2.0 design docs very closely. I had heard with interest about the new persistence layer, but hadn't done much other investigating. Today I spent a bit of time perusing some of the content, and the real purpose of the rewrite started to make sense to me.

AngularJS 2.0 is a concerted effort to make sure that Angular remains relevant in the coming front-end world dominated by Web Components.

Sea Change Is Coming

I've written before about how Web Components are revolutionary. I strongly believe that in a few years they will become the dominant paradigm for front-end development. Web Components are not, however, in direct competition with modern front-end frameworks like Angular, Ember, or React. Instead, they are a new set of foundational technologies that will enable radically different and more powerful ways of building applications in the browser.

How is this related to Angular 2.0? The evidence is plain. As I browse through the design docs, I see at least six that reference Web Components directly or allude to related subjects. The Angular team is taking everything they've learned about building an application framework and building a brand new one for the Web Components world.

This is a brave and risky decision, but one that I think has a greater chance to protect Angular's market leadership than threaten it. There is not (yet) an accepted set of best practices for using Web Components to build applications. Polymer works at a lower level than an application framework; in fact, it's quite likely that application frameworks will emerge that are built on top of Polymer.

If Angular 2.0 arrives on the scene as the first comprehensive application framework for Web Components, and it's also good at that job, it could see massive adoption, and not just from the existing Angular userbase.

What's Next?

There's no doubt that the recent firestorm will tarnish Angular's reputation a bit. Someone who is researching which framework to use today might see the uproar and decide to turn elsewhere. Open source projects are just as vulnerable to brand perception as companies, and I think the Angular team needs to get out in front of it. Firmly establish the basis and need for change while reassuring developers that 1.X users won't be abandoned wholesale. Acknowledge that incompatibility is a massive pain and demonstrate awesome new stuff that makes the pain worth it.

It's an exciting time to be building apps in the browser, but it's also a turbulent one. Angular has done a great job of introducing a huge audience to sophisticated front-end development, but the last couple years are just a warm-up act to the true front-end revolution. Angular 2.0 seems a bit crazy now. Looking at the bigger picture, however, it might just be crazy like a fox.

Update: Two Roads Diverged

Since I finished writing this post, two interesting and relevant bits of content have been published. Tom Dale wrote about The Road To Ember 2.0. The Ember team is taking a gradual, migration-focused approach to integrating new technologies like Web Components, DOM-based templating, and other new tech. They call this "Stability Without Stagnation." Henrik Joretag of Ampersand wrote to Optimize for change. It's the only constant about how they are taking the "lots of little modules" instead of an all-in framework approach.

These are both smart, valid, and potentially wildly successful approaches. The fact that there are different teams of smart people building software to make the front-end better, and that those teams have different and directly conflicting philosophies is fantastic.

Maintaining large, popular open source projects is really damn hard. It's even harder when that project is a framework, because they are so deeply intertwined with users' application code. If you move forward gradually, you risk stagnation. If you move forward in great leaps, you risk leaving behind those who don't have the time and energy to leap with you. Like most things, it's not a question of good and bad, it's a question of risk and reward, of tradeoffs.

It seems we're all cursed to live in interesting times.

Categories
Author
Subscribe to Angularjs