Fix TypeScript Autocomplete for RxJS Operators And Helpers In NodeJS

I have been working on a Node application, and wanted to use Reactive Extensions (RxJS). All previous interactions with it were in web apps that run in the browser after some SystemJS / Webpack massaging.

At first it looked OK. I could build an Observer, and subscribe to it. I tried to use some operators, and this is when I got stumbled.

The Problem

I had a sample Observable, and I wanted to call flatMapTo on it, but I couldn’t!

Autocomplete only showed the subscribe method, as below:

2016-04-19_07-05-23

Just importing the specific operator file (which modifies the Observable interface and adds the operator method to it) didn’t seem to get the operator autocomplete (or successful compilation at times) to work.

I didn’t want to have to add each operator manually anyway, and this is Node not browser, I don’t have to be picky about imports (and again, it didn’t work anyway).

Note:

I was specifically trying map(), which I was able to get to work with ES2015 targeting (I’m working with Node 5, which has fair ES2015 support).

But that’s because an Observable is also an Iterable object that you can loop over, like an array.

I was not able to get switchMap() (Rx v5), or even it’s v4 equivalent flatMapLatest() though, or any other operator than map() – before I noticed I was not even calling that as an operator.

The documentation suggested the following line.

<code>typings install rxjs-symbol-typings
</code>

But it only threw an error. Which was very weird, because I could find the typings registry entry with this very name.

There were other suggestions for other platforms, which didn’t work for me anyway!

I also struggled to find examples of using RxJS operators with even something like Angular 2. Hence I’m writing this blog post.

How To Get TypeScript Intellisense To Work With RxJS

The main key to working with this was using the “KitchenSink” Definition file. This was also confirmed by looking at:

Property ‘distinct’ does not exist on type Observable<CustomType>

I can use this no problem because I’m in Node and not much worried about the size of the code, etc.

However, this post was not enough to get it to work. I still had a lot to fiddle with. As I mention later, I tried many things, and everything I found working stopped working afterwards.

Until I could nail it down to the following steps:

Install From NPM

You can get that by

<code>npm install @reactivex/rxjs@latest --save
</code>

Make sure you got at least version beta.6, not beta.2.

Add Definition File

You can do this from your tsconfig.json, like:

<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true
    },
    "compileOnSave": true,
    "files": [
        // Typings autocomplete file
        "typings/main.d.ts",

        // RxJS autocomplete
        "node_modules/rxjs/Rx.KitchenSink.d.ts",

        // Your other files come here
        "sample-files.ts"
    ],
    "exclude": [
        "node_modules",
        "typings"
    ]
}
</code>

Or in each TypeScript file if you choose to, at the top of the file:

<code>///<reference path="./node_modules/rxjs/Rx.KitchenSink.d.ts"/>
</code>

Gotchas

For the most part, the previous steps are going to be enough. However, I have found a few more gotchas in different editors, most of them are around WebStorm, which is crazy, as outside Rx, it seems to be an awesome TypeScript IDE.

I like WebStorm because it has the best autocomplete in strings (like paths and imports), and in tsconfig.json (which is outdated in VS Code).

Also, the gotchas sometimes happen in VS Code anyway. I have been going crazy between the two, as soon as I get something to work, undo it and repeat the exact steps, it doesn’t work.

Operator And Type inference

Sometimes type inference doesn’t work. I have found VS Code to be better at this than WebStorm.

<code>var sample1$ = Observable.create(observer => {
    observer.next("Non-proper autocomplete");
    observer.complete();
});
</code>

In this example, autocomplete for sample1$. will give autocomplete for any, which is OK as it’ll accidentally give autocomplete for RXJS operators.

But if you want proper autocomplete:

<code>var sample2$ : Observable<string> = Observable.create(observer => {
    observer.next("It works");
    observer.complete();
});
</code>

Note the : Observable<string> bit.

Observable Helper Methods

These are methods like like of, range, etc. I have found their autcomplete to the worst, it’s very flaky at best.

A few things seemed to help, like importing from "rxjs/onservable".

<code>import {Observable} from "rxjs/Observable";
</code>

(Vs from "import {Observable} rxjs")

I have also found that doing import {Observable} works better than import * as Rx.

When everything fails, going to TypeScript compiler in WebStorm and building current file, or even restarting WebStorm (Yes!!) helps fix autcomplete issues, especially if you changed your references and imports a few times. It just gets confused and doesn’t work well until an IDE restart.

Disclaimer

Just in case it’s not obvious for those not familiar with TypeScript. I have been doing JavaScript for so long. I’m not the person who can’t code without a fully-functional autocomplete.

But since autocomplete is an essential advantage of going the TypeScript way, and I have been loving working with RxJS from the demos I saw, I wanted to take it as a challenge more than anything else to see what it would take to get this working.

A Quick 10-Min Video To Start Writing Angular 2 With No TypeScript Setup

Hello everyone,

In this video, I share a very simple tip that I earlier shared with a few Newsletter subscribers and ng-sydney members, about the easiest way you can get to play with Angular2, without worrying about shims, SystemJS, TypeScript, or RxJS.

I also give you another hint for when you want to create a “proper” project, not just a playground.

Too Long; Didn’t Read (Watch)

  • To start a new Angular2 playground, go to angular.io, scroll down to the hellow world example, and click the “TRY IN PLUNKER” button
  • If you need a proper project, just google “Minko Angular2 Seed”, click on the Angular 2 Seed Github repository, and clone that (maybe with flag --depth 1 for clean history)

Let me know if you have any questions.

You Don’t Just Claim Authority Over “Standard” JavaScript

I stumpled upon a contraversial website called standardJS.com the other day.

Originally I didn’t bother the name until a friend on social media commented on it, and then I looked more into the naming.

The website offers some guidelines for writing JS. It tackles a lot of areas with common disagreements like banning semicolons and defining tabs as 2 whitespaces.

However, as the domain shows, this is called StandardJS.com!!

This quickly reminded me of another story

Standard Markdown

In 2014, Jeff Atwood, a celebrity also known as CodingHorror, decided after many frustrations with fragmentation of Markdown Flavors, to create a Standard Markdown flavor.

This is how it started: Standard Flavored Markdown

And This is How it ended: Standard Markdown is now Common Markdown

You see, Jeff, being a celeberity, got his project very popular by just creating it. This also caused the flame wars to go strong. And the expected outcome to happen.

You’d think this should be a good lesson for future Open Source Standard projects, but it wouldn’t be software if we don’t just re-implement the same mistake every few years, would it?

Standard JavaScript

Then there is standardJS.com thingy. The creator writes the following in the FAQ (emphasis mine):

Q: But this isn’t a real web standard!

A: Of course it’s not! The style laid out here is not affiliated with any official web standards groups, which is why this repo is called feross/standard and not ECMA/standard.

But the domain is NOT FerossStandardJS.com , it’s just StandardJS.com.

Even worse, there’s a static analysis NPM package, that is supposed to help enforce the guidelines in Pull Requests etc., for repositories that implement the standard.

Guess what’s the name of the npm package?

Correct, it’s standard (Yes, No JS even, it is THE Standard!)

“I Disagree” As a repository label

Of course several people tried to object to the naming, via the most appropriate Github way to object to things, project Issues.

They called claiming the word Standard as “Obnoxious”, “Misleading”, and plain “Arrogant”.

All issues discussing the name went into a Github Issues label called “I Disagree“.

Middleground

I tried to do it differently, and suggest just changing the non-constrained standardJS.com domain naming.

My issue was quickly closed with the same label (in about 11 minutes), thinking that it disagrees with the project naming.

Once I explained it was about the domain (once more), it was opened, and marked as a Question.

Here it’s: Abandon / Redirect standardjs.com domain to something else

Thinking About It

The whole thing is a bit weird though. Isn’t?

One doesn’t just declare standard over NPM or JS without being in the official authorities for these. io.js didn’t call itself StandardNodeJS, even though it had old NodeJS contributors in its committee.

Am I crazy to think that we should have gone past this kind of issues?

Writing An Angular2 Component in Today`s JavaScript (ES5) – Beta Edition

With a lot of changes happening since Alpha 48 all the way to Alpha 55 (later labeled as Beta 0 as well), the way you write components in general, even in plain JavaScript has changed from what might have seen in other posts.

Then the beta was out. Learn about it here:
http://angularjs.blogspot.com.au/2015/12/angular-2-beta.html

For a hello-world app at least, things didn’t change in beta than in Alpha 55, here’s how to do it.

Loading Angular 2

Here are all the files we’ll need:

<code><script 
    src="https://code.angularjs.org/2.0.0-beta.0/Rx.umd.js"></script>
<script
    src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
<script
    src="https://code.angularjs.org/2.0.0-beta.0/angular2-all.umd.dev.js"></script>
</code>

If you played with Angular 2 alphas and JavaScript before, you’d have seen some Angular.sfx.*.js files. sfx used to refer to “self extractable”, meaning you don’t need a package manager to use it. It got renamed to umd, which I assume is like “Universal Module Dependency”.

Also, some parts were extracted from the core, like zone.js, the, the magic that saves you from things like scope digest cycle in Angular 1, into an angular2-polyfills.js file.

Finally, Reactive Extensions, a library that Angular 2 uses to replace promises and more, was extracted from Angular main bundle as well, while still copied to the CDN, as Rx.umd.js.

So, the steps to get what files to load:

I’m assuming if you are using ES5, you don’t want to even bother with NPM. So, I set the steps based on that.

  1. Go to AngularJS CDN https://code.angularjs.org
  2. Search for 2.0.0 and find the highest version folder. For example 2.0.0-beta.0.
  3. Look for the following files in the folder, and use them in order:
    1. Rx.umd.js
    2. angular2-polyfills.js
    3. angular2-all.umd.dev.js

This will give you the ng global variable, which is what we will you to define and bootstrap our components.

You will later want to include things like the “http” file and “router” file to use their corresponding functionalities.

Defining A Component

There are two ways we can use to define components in JavaScript:

Static Property

This should be familiar to you if you ever tried to write object oriented code in ES5:

<code>var HelloWorldComponent = function() {};

HelloWorldComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: '<h1>Hello Angular2!</h1>'
  })
];
</code>
  • You define poor-man’s class, ES5 style, as a function (the convention is to use PascalCasing for these).
  • You set a field called annotations on the function itself to be like a static class property. It’s the equivalent of attributes/annotations used in TypeScript.
  • You add the ng.core.Component annotation.
    That’s where you include the selector, template and other component properties just like in TypeScript. Except in ES5 you don’t have multi-line strings.

    • Note the PascalCasing. It’s another class.
    • The selector is almost always an element CSS selector. A custom element typically is lowercased with at least one hyphen - in it, like hello-world, which maps to <hello-world> in our HTML.
    • The template is just like the template in an Angular 1 directive (except with Angular 2 template syntax). You can also use templateUrl.
  • A couple of gotchas:
    • Note the part ng.core.Component. This is due to Angular splitting it’s code into different parts like “core”, “common”, “compiler”, “platform”, etc.
    • If you miss the new in there, it won’t work, and you will be scratching your head for quite a bit.

Fluent API

This tries to get even closer to TypeScript. It’ll either make you feel you have TypeScript already, or make you die to move to it!

<code>var HelloFlentApi = ng.core.Component({
  selector: 'hello-fluent',
  template: '<h1>Hello Fluent API!</h1>'
}).Class({
  constructor: function() {
  }
});
</code>
  • Notice the same ng.core.Component explained above
    • Gotcha: This time do NOT use new before it. Actually it will NOT work if you add new. Beware of this gotcha.
  • After that, you use Angular’s own Class class (pun intended).
    • The “constructor” field maps to the function in the first example.
    • Gotcha: You MUST add a constructor even if it’s just an empty function, or else it will not work.

Data Binding

This is worth its own article. For simplicity, let’s look at a simple ng-model example:

<code>var HelloFlentApi = ng.core.Component({
  selector: 'hello-fluent',
  template: '<h1>Hello {{name}}!</h1>' + '<input [(ngModel)]="name">',
}).Class({
  constructor: function() {
    this.name = "Fluent API";
  }
});
</code>
  • We used the two-way data binding syntax [(property)]=value.
    • the syntax [attribute]=”value” is used to bind from JS objects to DOM attributes and other directive attributes.
    • The syntax (eventName)=”handler” is used to bind from the DOM (like DOM events), to a JS function that handles the change/event.
    • As [] means JS => DOM, () means DOM => JS. [()] is used for 2-way data binding.
  • We said ngModel, not ng-model. This is a relatively recent and controversial Angular 2 change, that all component DOM attributes (Angular components or custom components), will use the camelCasing, instead of hyphen-separated (also known as kebab-casing).
  • In earlier Alphas, you needed to set a directives property to your component to use ngModel, ngFor, ngIf, etc. These are no longer required.
    (If you don’t know what that is, it’s dead anyway. Don’t bother for now)

Bootstrapping The Component

OK, let’s say we wrote the above components, and we want to use them. How would we do that?

The convention in Angular 2 is to have an application component. Something like:

<code>var AppComponent = ng.core.Component({
  selector: 'company-app',
  template: '<hello-world></hello-world>' + 
            '<hello-fluent></hello-fluent>',  
  directives: [HelloWorldComponent, HelloFlentApi]
}).Class({
  constructor: function() {}
});
</code>
  • Note that for us to include other custom components in our template, we had to add them to another property, called “directives”.
    We didn’t have to do this for the built-in things like ngModel.

Then in HTMl, we use the app component:

<code><company-app>
  Loading ...
</company-app>
</code>
  • It’s another Angular convention to put the default UI (like a loading indicator) inside the app component.
    Angular 2 will replace that with your template when it loads it.

Now, to make the magic happen, you need:

<code>document.addEventListener("DOMContentLoaded", function() {
  ng.platform.browser.bootstrap(AppComponent);
});
</code>
  • If you don’t know DOMContentLoaded event, you probably were doing a lot of jQuery. This is the standard equivalent of the jQuery “ready” custom event.
  • If you did this in previous alphas, you might notice that part ng.platform.browser.bootstrap.
    • I mentioned earlier that Angular2 functionality has been split into different parts. plaftorm is one of them (this is like a namespace in C#/Java – the convention for namespace casing is camelCasing).
    • Since you can use AngularJS with even something that is not HTML at all (like NativeScript for native mobile UI), that’s why (I guess) we need to select the “browser” platform to bootstrap it.

And that’s it. You get a nice application running!

Full Example

Here’s a complete application for easier read:

Using TypeScript Async/Await With Selenium NodeJS Bindings

In previous post I described how I used TypeScript with Babel to get my JavaScript Selenium tests to be executed by Node.

I wanted to dedicate this separate post to an example of the Selenium code that I wrote, because there are many tricks and gotchas that need your full attention.

That’s mainly around the use of async/await of course. Instead of write a paragraph about each piece of the code, I have embedded my points in the code itself.

The sample simply goes to the Angular2 Github repository, and reports the title and date of the first page of open issues in the repository.

<code>// Following `reference` comments allow Node & WebDriver autocomplete.
// This is needed as both are not written in TypeScript.
// You can download them via TypeScript Definitions package manager:
//      npm install tsd -g
//      tsd install node
//      tsd install selenium-webdriver

/// <reference path="typings/node/node.d.ts" />
/// <reference path="typings/selenium-webdriver/selenium-webdriver.d.ts" />

// If you are not using babel-runtime (see prev post), 
//      you can try this instead. You'll still need babel processing.
// This worked in atom-typescript, didn't work in gulp run.
// Not good to have to write it in every file anyway
require("babel/polyfill");

// The selenium-webdriver offers multiple exports
// Each of them works like namespace
// To use, you need:
//      npm install selenium-webdriver
import * as webdriver from "selenium-webdriver";
import * as chrome from "selenium-webdriver/chrome";

// This is optional good way to manage chromedriver binaries
//      npm install selenium-binaries
// You see I can mix `import` and `require` in same file!
var chromeDriverPath =
    require('selenium-binaries').chromedriver;
process.env.CHROME_DRIVER_PATH = chromeDriverPath;

// Shorten the names we'll use a lot
var By = webdriver.By,
    until = webdriver.until;

// Configure WebDriver. Nothing async yet.
// Could also move into next function no problem.
var driver = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome())
    .build();

// You can only use `await` inside an `async` function.
// Hence the IIFE (immediately-invoked function expression) wrapping
(async function() {

    // Some code to ensure browser is closed if I get an error
    // That's trial and error with Selenium, and googling...
    await webdriver.promise.controlFlow().on('uncaughtException',
        async function(e) {
            await driver.quit();
        });
    await process.on('SIGINT', async function() {
        try {
            process.exit();
        } finally {
            await driver.quit();
        }
    });

    // I'll store the results here then console log them.
    // I could log them directly, at 1st I didn't know how
    //      and now I'm keeping it to show more cool tips 
    var results = [];

    try {

        // Most WebDriver functions return special promises 
        //      that allow you to call the next function fluently:
        //      `driver.get(...).findElements(...)`
        // But that's not cool for debugging which part failed
        //      & doesn't work with loops, etc.
        // So, I `await` most of the `promise`s.
        await driver.get("https://github.com/angular/angular/issues");

        var issues = await driver
            .findElements(By.css(".table-list-cell.issue-title"));

        // This is worth its own post:
        // When I use `async` function in `map` (to use `await` in it),
        //      I get an array of promises, not results
        // So, I use Promise.all to
        //      get the results in one promise I can `await`
        results = await Promise.all(issues.map(async function(issue) {

            // Could have used `await` here or did it fluently
            // Just showing different styles.
            var titleContainer = issue
                .findElement(By.css(".issue-title-link"));
            var title = await titleContainer.getText();

            var dateContainer = issue.
                findElement(By.tagName("time"));
            var date = await dateContainer.getAttribute("title");

            return { title: title, date: date };
        }));

        // console doesn't get flushed inside `async` functions
        // Surprisingly, I can `await` it to work!
        await console.log(results);

    } finally {
        await driver.quit();
    }

} ()); // As mentioned above, the function executes itself
</code>

Prerequisites

In case you wonder, here are the packages used above, in a single NPM install command

<code>npm install selenium-webdriver babel selenium-binaries
</code>

This doesn’t involve the build configuration to get this compiled and running.

Check out my other post to learn how to setup the build for this.

Finally, I hope those two articles combined help you write your own asynchronous code with ease, with Selenium or any other purpose.

How To Use Babel And TypeScript, Together!

Use Case

The Selenium bindings for NodeJS are very nice that everything is a promise. When you are sending a command to the browser, this command might pass (say, return the element if found), or fail (say, trying to click an element that doesn’t exist), so, it’s a good fit for promises.

However, when I write tests, I think of them as a sequence of steps. With promises, the next step is always in a then() function.

But no one wants to keep nesting code like
x.then((y)=>y.then( (z)=>z.then(...) )).
Selenium extends promises so that you don’t have to do this all the time, but I soon hit limits (like loops).

Then I remembered reading about TypeScript support for async/await. When I tried it, the coding experience was nice, but I had to do a bit of setup.

Configuring Async / Await In TypeScript

I had to turn some experimental flags on, and target ES6. The easiest way to do this is to create a tsconfig.json file in the directory where I run tsc (TypeScript compiler) from. Here’s what mine mainly looked like:

<code>{
    "compilerOptions": {
        "target": "ES6",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "experimentalAsyncFunctions": true
    },
    "files": [
        "app/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}
</code>

Node, ES6, Babel, And ES7

I tried to run the output of TypeScript in Node, but it didn’t work. It complained about import statements. It seems that Node doesn’t understand ES6 module system, not very surprising given it has its own module system too, commonJS.

TypeScript can target commonJS, but async/await is only supported when targeting ES6.

So, I decided to take the output through Babel before I run it with NodeJS.

Side Note: Babel already had support for async/await as it’s also coming to ES7. But by the time I got to that I was already happy with my autocomplete experience in TypeScript that I wanted to continue with this setup.

Using Atom Editor

It was so easy to get babel to work with TypeScript in Atom. I had atom-typescript package installed, and it suppoted an extra property in tsconfig.json:

<code>"externalTranspiler": "babel"
</code>

This is a NON-standard TypeScript property. But it allowed me to work very happily with Atom, and my .ts files processed via TypeScript and Babel whenever I save them.

This approach had a main no-go issue though. Anyone who pulls my code should be able to get it to work without me committing the “auto-generated” JS files, and without the others having my Atom setup, and building the project from Atom. This won’t work in CI build server.

Using Gulp Tasks

At this point, I decided to have a gulp task that does the transformation. It turned out to be very easy.

The following code sets gulp to process all .ts files in “app” folder via TypeScript and Babel, and save them as .js files:

<code>var gulp = require("gulp");
var ts = require("gulp-typescript");
var babel = require("gulp-babel");
var rename = require("gulp-rename");

gulp.task("ts-babel", function () {
    // Using my existing tsconfig.json file
    var tsProject = ts.createProject(__dirname + "/tsconfig.json");

    // The `base` part is needed so
    //  that `dest()` doesnt map folders correctly after rename
    return gulp.src("app/**/*.ts", { base: "./" })
        .pipe(ts(tsProject))
        .pipe(babel({
            optional: ["runtime"]
        }))
        .pipe(rename(function (path) {
            path.extname = ".js";
        }))
        .pipe(gulp.dest("."));
});
</code>

You might wonder why did I do both transformations in the same task. That’s mainly to save disk writes, so that I don’t have to write an ES6 file that’s never going to be used except for Babel processing.

If you want to split them, should be easy, like:

<code>var gulp = require('gulp');
var ts = require('gulp-typescript');
var babel = require('gulp-babel');
var rename = require('gulp-rename');

gulp.task('tsc', function() {
    var tsProject = ts.createProject(__dirname + '/tsconfig.json');
    return gulp.src('app/**/*.ts', { base: './' })
        .pipe(ts(tsProject))
        .pipe(rename(function (path) {
            path.extname = '.babel';
        }))
        .pipe(gulp.dest('.'));
});

gulp.task('babel', function() {
    return gulp.src('app/**/*.babel', { base: './' })
        .pipe(babel())
        .pipe(rename(function (path) {
            path.extname = '.js';
        }))
        .pipe(gulp.dest('.'));
});

gulp.task('ts-babel', ['tsc', 'babel']);
</code>

NPM Prerequisites

To run these, you need to install the needed packages:

<code>npm install gulp gulp-typescript gulp-babel gulp-rename babel-runtime --save-dev
</code>

Example & Conclusion

So, that’s all it takes to run the compilation/transpilation. You might want to hook this into nodemon or some gulp-watch task etc., but this is not specific to TypeScript or babel in any way, so, I thought it’s not worth mentioning here.

If you are curious about the code that I needed this setup for, check out my sample code post.

Angular 2 Browser Support Announced For IE9, Android 4.1, And iOS 7.1

Do you want to try out Angular 2 and TypeScript?
Would you like to do it without all the hassle of build configuration?

Here’s a FREE 10 minutes video to help: Start Writing Angular 2


P.S.
Don’t worry. I’m not trying to sell you anything :)
Not even asking you to sign up to my FREE newsletter in the video.

While Angular 2 promised a lot of cool things, it also came with a big disappointment for some developers. It was browser support.

Angular’s future centric approach made it target only evergreen browsers on the desktop. That meant that the only Internet Explorer version it was going to support is IE 11, which meant that developers targeting IE 9 or IE 10 are out of luck.

It also raised the question about mobile browsers. The only builtin evergreen browser rendering engine on mobile is Chrome in some Android 4+ devices. The team didn’t originally provide a mobile strategy.

Luckily for all of us, this has just got changed :)

Today Brad Green from the AngularJS team announced the browser versions Angular 2 is going to support, on both desktop and mobile:.

Can you see it? YES, that’s IE 9 in there!

I couldn’t believe it that I went on to confirm from Brad:

The mobile support is also awesome, as you can see, going all the way back to Android 4.1 and iOS 7!

How To Track

As per the exact announcement:

You’ll be able to track Angular 2 support and progress vs current browsers by looking at the status page of the browser testing build, available at:

https://saucelabs.com/u/angular2-ci

The results are shown in a little widget image in the Angular 2 repository homepage, as Brad notes. Which is of course github.com/angular/angular.

Do not panic if you see some red instead of green in there by the way, as Angular 2 is obviously still work in progress.

Using `bindToController` & `controllerAs` Together In The Same Angular 1.4+ Directive

When I looked for articles about how to use bindToController in directives, I saw a lot of code samples that look like:

What Doesn’t Work?

<code>angular.directive("test", function() {
  return {
    bindToController: true,
    scope: { message:'=test' },
    controller: function() {},
    controllerAs: 'myCtrl'
  };
});
</code>

With that, I should be able to use the directive in the following way:
(not using a directive template here, maybe that’s what others tested!)

<code><div ng-init="parentValue = 'Success'">
  <div test="parentValue">
    {{myCtrl.message}}
  </div>
</div>
</code>

And that should display success, right? It doesn`t!

Things I tried:

  • Defining the controller separately via angular.controller(...), vs making it a function in the directive definition object (DDO) as above

  • In the scope, changing the property name to be different from the directive name.

What Works? The solution

Simply, swap the values of bindToController and scope!

Like this:

<code>angular.directive("test", function() {
  return {
    scope: true,
    bindToController: { message:'=test' },
    controller: function() {},
    controllerAs: 'myCtrl'
  };
});
</code>

I already read that in Angular 1.4 you can use the bindToController property similar to how you use the scope property, meaning you use it to define what properties are created in the new scope.

I still thought I need scope: {} though to make that new scope magic work. But it turned out that this was actually ruining it. All I needed was to set it to true to have a separate scope.

Complete Sample

I have kept it stupid simple so that the main point is not lost.

<code>angular.module("demo", [])
  .controller("sampleCtrl", function() {
    this.sampleValue = 'success';
  })
  .directive("test", function() {
    return {
      scope: true,
      bindToController: { message:'=test' },
      controller: function() {},
      controllerAs: 'testContext'
    };
  });

document.addEventListener("DOMContentLoaded", function() {
  angular.bootstrap(document, ["demo"]);
})</code>

See the Pen bindToController Sample by Meligy, Mohamed (@Meligy) on CodePen.

Here’s what AngularJS Team Recommended Developers Do In AngularU Keynote

From watching the AngularU conference keynote and Q & A session, I noted some of their hints and answers into a list of recommendations

  • Use the latest stable 1.x version of Angular, at the moment 1.4
    No surprise, ha?!

  • Use the latest stable TypeScript.

    • Use the official Angular type definition file when using TypeScript.
    • Note that TypeScript 1.5 beta mainly gives you decorators/annotations, which are only relevant for Angular 2 anyway.
    • Alternatively, at least move to ES6, using Babel or Traceur
      • Both babel and tracer support annotations.
 
  • SystemJS seems like package manager of attention today, as it allows you to load libraries regardless of where they are packaged
    Obviously they are also checking all popular packaging options.

  • Follow John Papa’s Angular styledguide.
    That was a BIG endorsement IMHO, coming from the official team, even that it was kind-of in passing.

  • Use ui-router until the new Angular router (I think now Component Router) is ready.
    This was a very subtle recommendation, probably just due to the new router not being ready, and lack of other equivalent options.
    At least they said they looked at it for the new router, which wasn’t the case when I checked in March!

Disclaimer: The list is my personal interpretation – You can watch the full video and judge the correctness / accuracy.

AngularU, NPM 3, & Hosting Recommendations — Issue12 — Meligy’s AngularJS & Web Dev Goodies

Hello,

For the new ones around here, this is @Meligy writing this issue of GuruStop.NET Newsletter for JavaScript developers, especially those working with AngularJS.

I’ll mix in a few quick links with the ones I describe, for a change.

Please reply back and tell me whether you think this is a good idea.

Let’s jump to today’s picks:

AngularJS

AngularU Videos

You probably heard about AngularU, another big Angular event like ng-europe, with speakers from within and outside the Angular team.

There is a ton about Angular 2 (roadmap, server rendering, forms, TypeScript), but also several topics about Angular 1.x for both coding techniques and libraries, and even integration with different backends.

Angular 2

Contribute to Angular 2 [“community-help” Github Label]

In an up-for-grabs way, Angular 2 repository issues now has a special label for issues that the team expects external contributors from the community might be able to work on easily.

Check the list. You might find something that you can do!

React Native and NativeScript Integration [Article]

A narration from the “AngularJS 2 Roadmap” in AngularU that gets you the news pieces directly. It also links to the Angular 2 Rendering Architecture document.

Styling Angular 2 components [Article]

Angular 1.x

gulp.js starter for AngularJS SPAs

A scaffold starter kit for Angular applications that uses gulp and bower and tries to set a few more things than folder structure (which seems nice) like fonts, etc.

Similarly, here’s another one that uses NG6: ES6 + JSPM (or Webpack).

Angular Formly [Library]

This one seems to be getting A LOT of attention. I see several people sharing it, and I hear about it in the Angular Air podcast.

Give it a look, or check this article about how to use it.

New features in AngularJS 1.4, AngularJS Meetup South London [Article]

Using Angular 1.x With ES6 and Webpack [Article]

More traps, anti-patterns and tips about AngularJS promises [Article]

Directives (Angular 1.x)

A Guide To Transclusion in AngularJS [Article]

Very good explanation of templates and, obviously, transclusion.

Using NgModelController with Custom Directives [Article]

From GuruStop.NET

Using track by correctly with Angular 1.4 select ng-options

This is a one year follow up of the most read post ever in my blog, about select element quirks in AngularJS, How to set the initial selected value of a select element.

AngularJS is not working at all, & angular.bootstrap() throws weird errors

I was getting ready for another post, bootstrapping my demo angular module manually, and I just couldn’t get Angular to work. After a bit of frustration, turned out I needed to run this after DOMContentLoaded was fired.

ReactJS

Nvigating the React Ecosystem [Article]

We know React is just a template / view library. What other tools and libraries are there that make building whole apps with it possible?

The pursuit of high performing, easily maintainable React apps [Article]

JavaScript

Debugging

Useful Javascript debugging tips you didn’t know [Article]

Being able to monitor function calls in the console is nice. Also, if you didn’t know about, black boxing library scripts is VERY nice for debugging jQuery / Angular / Polymer / etc. apps.

ES2015 / ES6

In case you don’t know, the committee that releases the JavaScript standard (EcmaScript standard) decided to have version names after the year of release.

So, the official name for EcmaScript 6 is actually EcmaScript 2015.

Announcing “Exploring ES6” [New Book] [Freebie]

The book is free for online reading, and you are encouraged to buy downloadable formats to support the author.

It’s high on my reading list. This guy’s blog is a very good resource for JavaScript info.

JavaScript.com

Code School learning website has aquired the domain and put some nice free learning materials in there for starters.

5min ES6 Intro (With Babel) [Video]

Setting up an ES6 Project Using Babel and Browserify [Article]

NodeJS

NPM 3.0 [News]

BPM v3 is released with label “latest” and actual description “beta”. It’s going to be side by side with future v2 releases, but at least it should fix several common issues with v3.

Gulp

Getting started with gulp [Article]

Good article that was updated a lot to keep up with Gulp.

Web Design

Improving Web Fonts Performance [Slides]

Bootstrap Sass Installation and Customization [Article]

Designing User Interfaces for Your Mother [Article]

Text Editors / IDEs

Visual Studio

JavaScript Editor Improvements in Visual Studio 2015 [News]

There’s some about AngularJS & requireJS support, but my most favourite is integrating JsDoc into intellisense (autocompolete).

JsDoc fairly common in documenting JS libraries, so, a lot of them will benefit greatly from it.

@Ch9 Connect(“On Demand”); [Videos]

Channel 9 has a nice new series of various length videos about Visual Studio 2015, and other related .NET, Azure, and programming language topics.

I watched a few and liked them a lot.

Visual Studio Tools for Apache Cordova – Samples and Docs [Code Samples]

Atom

Github’s Atom free / open-source text editor.

Facebook open-sources its Nuclide IDE based on GitHub’s Atom text editor [News]

Github Atom 1.0 released (And very cool video)

Let’s see how long it will take other editors based on Atom to be in sync with it!

Software Design

Martin Fowler: Monolithic apps first, microservices later [Article]

In his own words “Almost all the successful microservice stories have started with a monolith that got too big and was broken up”.

The introduction to Reactive Programming you’ve been missing [Article]

Web Hosting

Where should I host my blog (WordPress or other), if I want my own server / VPS?

One of the blog posts I wanted to write for long time actually. In short, for Windows, use SoftSys Hosting, for Linux, use DigitalOcean, and maybe check BlueHost.

I got a comment in email saying why WordPress instead of static file based blog, but that might be a topic for another post!

Misc / Fun

DebConf14: QA with Linus Torvalds (August 2014)

One of these random Youtube autoplay videos, but I found it interesting, not having heard a lot from Linus before.

What happens when you type google.com and press enter? [Article]

How deep do you wnat to take the answer to? Send a Pull Request, it’s a Github repo :)

There’s also other variations on Quora and on StackOVerflow.

Community Casts [Videos]

A video collection website that seems to have around 100 AngularJS videos, and similar number or general JavaScript videos and for C#.

Seems like there are some people actively adding videos to it as several videos are added just hours before I checked it.

If you liked this newsletter

Donate?

You might consider buying me a coffee, or two ;)

You can donate to the newsletter via Paypal.

But most importantly

You can reply to me and make this newsletter better:

  • Is the current monthly frequency OK, or should it be closer to weekly or bi-weekly?

  • Do you like the content? Do you want more AngularJS content? Or less? More JavaScript? C# / .MET?

  • If uou find a good article, video, library / tool, or anything else that can fit into this newsletter, why not reply and share the love? Thanks :) :)

Apart from that…

See you next one :)

@Meligy –– GuruStop.NET