DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Preparing for Angular 2

Preparing for Angular 2

A Collection of Best Practices to be Ready For Angular 2

Juri Strumpflohner user avatar by
Juri Strumpflohner
·
Aug. 13, 22 · Tutorial
Like (0)
Save
Tweet
Share
3.51K Views

Join the DZone community and get the full member experience.

Join For Free

I'm sure you heard about angular 2 and that it will be totally different. Forget everything you know and start from scratch. Jokes aside, if you have taken a closer look, you already know that, yes, it will be new, things will be different (as it's mostly the case with new stuff), but many concepts will still be there. 

Well, as angular 2 starts getting more and more concrete, articles, videos, and podcasts get published that contain lots of useful information on how to get prepared for an eventual migration scenario. I use this article to collect such best practices for myself and obviously to share them with you!

Totally feel free to submit new practices in the comments or directly submit a pr in the GitHub repo for my blog.

Preparing For Migration 

It is wise to prepare yourself for the migration of services over from one provider to another anytime it looks like this is likely to happen. One of the ways that you can do this is by backing up all of the work that you have already contributed to a project to ensure that it is ready to go to handle your next project as it comes along. 

When you do this, you are taking concrete steps towards an end goal that is defined and has real value to it. Make sure you think about exactly what you will do to get all of your files and documents where they need to go. 

The reality of the situation is such that you need to take every step within your power to change the way that you process data and do so while causing as little disruption as you possibly can. 

This is never easy, but you can find that you are better able to handle your projects when you have prepared for them in advance. 

get rid of $scope: controller-as syntax 

Definitely switch over to the controller-as syntax and get rid of $scope in your controller files as well as in the templates.

<div ng-controller="personcontroller as personctrl">
    <div ng-repeat="person in personctrl.people">
        {{ person.name }}
    </div>
    <button ng-click="personctrl.add()">add</button>
</div>

angular
    .module('demo', [])
    .controller('personcontroller', personcontroller);

function personcontroller(){
    this.people = [
        {
            name: 'juri'
        },
        {
            name: 'steffi'
        }
    ];
};

First of all, angular 2 won't have any concept of $scope, and then - especially in the HTML - using the controller-as syntax avoids a lot of headaches when it comes to nested controllers.

Links

  • angular style guide

  • exploring angular 1.3: binding to directive controllers

Use Directive Controllers Where Possible

when you create new angular directives, you actually have different possibilities where to define your logic:

angular
    .module('demo', [])
    .directive('persondisplay', persondisplaydirective);

function persondisplaydirective(){
    return {
        compile: function(element, attrs){
            // implement logic
        },
        link: function($scope, ielement, iattrs){
            // implement logic
        },
        controller: function(){
            // implement logic
        }
    }
}

When should we use which?? That's a common question among angular devs. You can find some suggestions on the angular docs and in various online communities, but it's not always that clear.

Angular 2 removes all of these, and you'll have a component (directive) and a controller class associated with it. As an obvious result, people suggest using "directive controllers" wherever possible.

angular
    .module('demo', [])
    .directive('persondisplay', persondisplaydirective);

function persondisplaydirective(){
    return {
        controller: function(){
            // implement logic
        },
        controlleras: 'vm'
    }
}

From his perspective:

  • No, you shouldn't avoid them per se. the point is, as long as you do stuff that hasn't to be in compile/pre/postlink, put it in ctrl

  • In other words, in most cases, you actually don't need to deal with compile/link. Controller gives you everything you need

  • except for cases like ngmodelcontroller, which registers itself at ngformcontroller during prelink

  • However, when controller is enough, use that. You don't have to deal with rather complicated compile/link things.

  • In addition, it's much more aligned with the philosophy behind angular 2 components. I recommend using controllers where possible.

  • Also easier to test!

Note that one issue when you use directive controllers is often on how to reference the directive scope properties from within the controller - since we should possibly avoid $scope. since angular v1.3 there is the boolean bindtocontroller property, and recently, in v1.4 they've even improved it s.t. you can write things like:

return {
  restrict: '...',
  bindtocontroller: {
    val1: '=',
    val2: '@'
    ...
  },
  controller: function($log){
    // access them with
    $log.debug(this.val1);
  }
}

There's a nice article on thoughtram about that. Follow the link below.

Links

  • exploring angular 1.3: binding to directive controllers

Prefer Components Over Controllers

Angular 2 follows the current trend of web components. Thus, it won't have autonomous controllers anymore, but just in conjunction with so-called components. An angular 2 app is a tree of nested components, with a top-level component being the app.


So rather than having controllers, start to create such widgets or components that are autonomous. In angular 1. x, we know them as directives. Search for template-dependent controllers and try to move them into separate directives. for example, refactoring the previous example, we could get something like this:

<div ng-controller="personcontroller as personctrl">
    <!-- personcontroller scope --> 

    <people-list people="personctrl.people">
        <!-- personlistcontroller scope here -->

        <div ng-repeat="person in personlistctrl.people">
            {{ person.name }}
        </div>

        <button ng-click="personlistctrl.add()">add</button>
    </people-list>
</div>

Note that the personcontroller passes in the data required by our list component. Thus it remains fairly re-usable. all it does is create the UI functionality.

angular
    .module('demo', [])
    ...
    .directive('peoplelist', peoplelistdirective);

function peoplelistdirective(){
    return {
        controlleras: 'personlistctrl',
        controller: function($scope, $attrs){
            this.peoplelist = $scope.eval($attrs.people);

            this.add = function(){
                // implementation
            }.bind(this);
        }
    }
}

Use Observables Instead of $watch

David east recently spoke at angular u on how to prepare for upgrading to ng 2. What's particularly interesting is his usage of rx.js to avoid $watch.

angular.module('demo', [])
    .service('peopleservice', peopleservice);

function peopleservice() {
  var peoplesubject = new rx.replaysubject();

  var service = {
    subscribe: function(subscription) {
      peoplesubject.subscribe(subscription);
    },
    add: function(people) {
      people.push({
        name: 'name ' + (people.length + 1)
      });

      // broadcast
      peoplesubject.onnext(people);
    }
  };
  return service;
}

at this point, on the  peoplecontroller  one can subscribe to the changes

function personcontroller(peopleservice) {
  var vm = this;
  vm.people = [];

  peopleservice.subscribe(function(people) {
    vm.people = people;
  });
}

in the  people-list  directive, that same people service can be used to broadcast new changes

function peoplelistdirective() {
  return {
    controlleras: 'peoplelistctrl',
    controller: function($scope, $attrs, peopleservice) {
      this.people = $scope.$eval($attrs.people);

      this.add = function() {
        peopleservice.add(this.people);
      }.bind(this);
    }
  }
}

See the sample functionality on plunker

Presentation by David east on preparing for angular 2:

  • video:  https://www.youtube.com/watch?v=kwz7iam35um 
  • source code:  https://github.com/davideast/angularu-a2-migration 
AngularJS

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • GitLab vs Jenkins: Which Is the Best CI/CD Tool?
  • Practical Example of Using CSS Layer
  • Integrate AWS Secrets Manager in Spring Boot Application
  • Fixing Bottlenecks in Your Microservices App Flows

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: