× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Future ready angular.js code

Daniel Olano
Aug 20, 2015
<p>Angular 1.x has been around for quite some time making our lives easier and many people are just starting to learn it because is trending, but there's a wave of new frameworks already at our doors and that makes us wonder if it's worth learning angular.js.<br> Fear not! I think it's definitely worth it. Next-gen frameworks are still under heavy development which means ng1 still has a lot to offer and will be around for some time. What we can do in the meantime is to get ready writing code that will be easier to migrate.</p> <p>So how do we write this future proof, easy to migrate angular code?</p> <p>Short answer: ECMAScript2015-2016. By writing your JavaScript code with the newer syntax you have most of your migration done, just use as much new goodness as possible and as less angular only code as possible.</p> <p>Check the next example:</p> <pre><code class="language-javascript">export class ShoppingCart { items = []; add(item) { this.items.push(item); } delete(item) { let i = this.items.findIndex(i =&gt; i.id === item.id); this.items.splice(i, 1); } get total() { return this.items .map(i =&gt; i.price) .reduce((a, b) =&gt; a + b, 0); } }</code></pre> <p>A simple and nice JS class with no dependencies on any framework, this code is ready to be used in angular.js or any other framework. How? </p> <pre><code class="language-javascript">import {ShoppingCart} from 'shopping-cart'; angular.module('app', []) // use it as a controller .controller('ShoppingCart', ShoppingCart) // or as a service .service('ShoppingCart', ShoppingCart) // or as a custom elment(directive) .directive('ShoppingCart', function() { return { scope: {}, restrict: 'E', controller: ShoppingCart, controllerAs: 'cart', bindToController: true, template: `&lt;div ng-repeat="item in cart.items"&gt;&lt;/div&gt;` } })</code></pre> <p>... To be continued.</p>
comments powered by Disqus