Essential Tips and Tricks for AngularJS Developers

AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. AngularJS lets you extend HTML vocabulary for your application.

At the onset, you may find AngularJS easy to start but a large part of the code hides behind the abstraction layer that even the experienced developers wouldn’t like to explore due to its sheer size and complexity. Hence, in this article we’ve brought up some of the best tips and tricks for AngularJS developers. Also, it’ll include best practices for writing AngularJS code and address a few of the debugging techniques as well.

1. Optimized Code Structure.

As someone rightfully said, “Without a solid foundation, you’ll have trouble creating anything of value.“. And as is the case with many of us who begin writing code to finish but don’t focus on the maintainability. Hence, you must plan for everything starting from the folder structure for your code. Here is a sample code structure for an AngularJS project that you may follow.

  • Create an “app” folder – the root of your project.
  • Place all your shared data in the “app/common” folder.
  • Put all your components files inside the “app/components” folder.
  • All of your resources should go inside the “assets” folder.

Recommended Code Structure.

app/
----- app.module.js
----- app.routes.js
----- common/ // re-usable components
---------- controllers
---------- directives
---------- services
---------- html
----- components/ // every component is a mini Angular app.
---------- home/
--------------- homeController.js
--------------- homeService.js
--------------- homeView.html
---------- cart/
--------------- cartController.js
--------------- cartService.js
--------------- cartView.html
assets/
----- img/ // media files for your app
----- css/ // styling files
----- js/ // script files written for your app
----- libs/ // third-party libraries e.g. jQuery, Underscore, etc.
index.html

2. Understand Scope In AngularJS

The scope is something which binds the HTML with the JavaScript. It’s an object created by AngularJS to access the methods and properties of the controllers and directives. It includes a lot of handy information which is quite useful for debugging purpose.

  • To access scope, first of all, you need to get to the target element. It is easily doable with the help of Chrome’s dev tools. Just inspect the web element and switch to the console tab.

  • There you can type $($0) or angular.element($0) to print the element. And then can use $($0).scope() to get to the scope object.

  • With the help of scope, you can know its whereabouts like its parents [$($0).scope().$parent] or parents of parents [$($0).scope().$parent.$parent] etc.

  • If the selected element is a directive having isolate scope, then use $($0).isolateScope() to determine its scope.

  • Also, using the $($0).scope().<Property Name> will return the value of that property.

  • If you wish to check if the scope includes a property or not, then use the $($0).scope().hasOwnProperty(‘<Property Name>’).

3. Restrain From Doing DOM Manipulation.

You should not carry out any DOM Manipulations inside controllers, services or anywhere else. However, you can have them working in the directives. Or the best is to avoid them as whenever there is any, else AngularJS will trigger events to maintain the application state. And It’ll lead to extra overhead for the application.

4. Use Service To Share Data Between Controllers.

Sometimes, you have two or more views in different routes that need access to some status variable. Or you may have multiple components which need access to the same piece of data.

In such cases, the best approach to share data between controllers is by creating a dedicated service for this. See the below example.

Let’s say we’ve two controllers dc1 and dc2. And exchange is the name of our data service.


var myApp = angular.module("myApp", ['beginexchange']);
 
myApp.controller("dc1", ['$scope', 'exchange',
    function ($scope, SharedDataService) {
    $scope.Product = SharedDataService;
 
    }]);
 
myApp.controller("dc2", ['$scope', 'exchange',
    function ($scope, SharedDataService) {
    $scope.Product = SharedDataService;
 
}]);

Now, you can implement the view using the controllers in the following fashion.

<div ng-controller="dc1">
            <h2>In Controller 1</h2>
            <input type="text" ng-model="Product.name" /> <br/>
            <input type="text" ng-model="Product.price" />
            <h3>Product {{Product.name}} costs {{Product.price}}  </h3>
</div>
<br/>
<div ng-controller="dc2">
            <h2>In Controller 2</h2>
            <h3>Product {{Product.name}} costs {{Product.price}}  </h3>
</div>

5. Don’t Use Controllers For Presentation Logic.

The recommended development model in AngularJS is the MVC. It consists of a model, view, and controller. When you add presentation code in the controller, then you are breaking the integrity of the layers. Also, it could lead to unmanageable code. And it would become hard for other developers to debug. So, if you require a change in any HTML element or any DOM manipulation, then you should do it in the presentation layer.

6. Use Track By For Quickly Displaying List Items.

You can control the frequency of rendering lists by using the Track By feature. Otherwise, displaying the list will require the DOM to reload for every item in the list.

See the below example.

<div ng-repeat="listitem in empList">
</div>

The above approach will make your code less efficient. Hence, you should be using the following code.

<div ng-repeat=" listitem in empList track by item.empid">
</div>

The code above still follows the same process. But it would display the list faster and make the application more efficient. As it is using the unique key instead of using a random one.

7. Adapt ControllerAs Approach.

In spite of using the scope as a container, it’s better to use a controller as itself.

For your information, in controllers, it is no longer suggested to use the “$scope” variable. But we can assign everything to a controller object like this.text=” “. And in HTML templates, we should just set a name for our controller variable.

ng-controller=”MasterCtrl as ctrl"


It would work without any issue. However, there could be people who may oppose this approach but I think it is useful for developers who faced problems in following the scope based approach.

You can use the controllerAs property inside the directive signature.

app.directive('Directive', function () {
    return {
      restrict: 'EA',
      templateUrl: 'temp.html',
      scope: true,
      controller: function () {},
      controllerAs: 'vm'
    }
});

Or also use it for controllers via $routeProvider in the following manner.

app.config(function ($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'hero.html',
    controllerAs: 'hero',
    controller: 'HeroCtrl'
  })
});


8. Integrate Less To Produce CSS.

LESS, which is a CSS pre-processor and provides features like mixins, operators, and functions. Many developers recommend the use of Less for web development with AngularJS. While working with it, there are a lot of things which you can achieve.

  • It offers high-level styling syntax to allow web developers to produce advanced CSS.

  • LESS preprocessor compiles into standard CSS before the browser begins rendering a web page.

  • Pre-compiled CSS files can be easily transferred to a production web server.

9. Use Built-In Validations In AngularJS.

AngularJS embeds an excellent feature of auto-validating your form. And eventually, this ability can become the backbone of any application that receives user inputs.

Usually, the validation of a form goes through a chain of code blocks. They include multiple “if, else if…” which leads to undesired complexity. In this approach, the user has to submit the form a no. of times to handle one validation error after the other.

However, AngularJS brings a different way of form validation which happens as the user fills it out. And all of these validations are inherent in Angular JS in the form of directives.

10. Avoid Filters With Large Arrays.

Filters run on each digest loop and create a new array every time they execute. In such cases, prefer to watch your list and do filtering upon detecting a change.

See this example of a bad use of filters in a digest loop.

<li ng-repeat="item in heroList | myHeroSortFilter"></li>


Whereas, now see a good example.

In Controller.

$scope.filteredItems = $scope.items;
$scope.$watchCollection('items', function () {
    // Apply filter on change detection
    $scope.filteredItems = myHeroFilter($scope.items);
});

In HTML.


<li ng-repeat="item in heroList"></li>


11. How To Detect If Property Changes.

Here is the sample code that monitors a property. It’ll print logs on the console.

var hero = {a: 2};

var _prop = obj.prop;

Object.defineProperty(prop, 'prop', {
 get: function () { return _prop; },
 set: function (val) { _prop = val; console.log('Property changed.'); }
});

12. How To Detect If An Item Changes In A List.

There could be two ways to achieve it. First of all, let’s see the bad example. The downside is, it’ll create copies of the object with each comparison.


$scope.watch('empList',
    function watchListener() {
        // Print a message if the reporting of any employee changes.
    }
}, true);

Now, let’s see the approach that you should use.


$scope.watchCollection('empList',
    function watchListener() {
        // Print a message if the reporting of any employee changes.
    }
});

13. Slow Down The Watchers From Being Called.

For delaying the execution of watchers, we can use the “debounce” property.


<input type="text" name="empName"
ng-model="emp.name"
ng-model-options="{ debounce: 100 }" /><br />

The above code will change model value only after waiting for 100 ms after the last change happened in input value.

14. Select An Element By ID Or Class.

For selecting the element using ID, use the following code.

angular.element(document.querySelector('#id'))


For selecting the element based on class name, use this code.

angular.element(elem.querySelector('.classname'))


15. Use Multiple Controllers In Separate Modules.

If you have multiple controllers in separate modules, then you can still use them inside a single module. However, you’ll need to include them as dependencies of your main module.


var dc1 = angular.module('dc1', []);
var dc2 = angular.module('dc2', []);
var app = angular.module('app', ['dc1', 'dc2']);

dc1.controller('dc1', function ($scope) {
    // Place your controller code here
});

dc2.controller('dc2', function ($scope) {
    // Place your controller code here
});

Conclusion

The above tips can be a good foundation for your future applications. These will help you improve skills and grow your knowledge in AngularJS. Also, you can improve productivity by turning your focus on the core business logic of your project.

Thanks for reading !

#angular #angularjs #javascript

Essential Tips and Tricks for AngularJS Developers
1 Likes14.00 GEEK