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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Dependency Injection
  • Hints for Unit Testing With AssertJ
  • Code Review That Matters: Tips and Best Practices
  • Fighting Climate Change One Line of Code at a Time

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • How to Merge HTML Documents in Java
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. AngularJS Coding Best Practices

AngularJS Coding Best Practices

By 
Ajitesh Kumar user avatar
Ajitesh Kumar
·
Sep. 08, 14 · Interview
Likes (4)
Comment
Save
Tweet
Share
74.2K Views

Join the DZone community and get the full member experience.

Join For Free

This article lists some of the best practices that would be useful for developers while they are coding with AngularJS. These are out of my own experiences while working on AngularJS and do not warranty the entire list. I am sure there can be more to this list and thus, request my readers to suggest/comment such that they could be added to the list below. Found some of the following pages which presents a set of good practices you would want to refer. Thanks to the readers for the valuable contribution.

  • AngularJS Style Guide
  • App Structure Best practices

Initialization

  • One should try and place the <script> tag including the angular.js and related angular scripts at the bottom of the page to improve the app load time. This is because the HTML loading would then not be blocked by loading of angular.js and related scripts.

Expressions

  • Complex javascript code should be made as a method in the controller (added as a method to the $scope) and then, should be called from the view. This is unlike putting the complex Javascript code as Angular expressions, right, in the view.

Controllers

  • With real applications, one should avoid creating controllers in the global scope. Rather, one should use “.controller” method of the Angular Module to work with $scope object. Take a look at the sample code below illustrating this point:

Controller defined in the Global Scope:

function HelloController( $scope ) {
$scope.name = "Guest";
}

Controller defined using “.controller” method (Recommended way)

var helloApp = angular.module( "helloApp", [] );
helloApp.controller( "HelloController", function($scope){
$scope.name = "Guest";
} );
  • The controllers should only be used to setup initial state of the $scope object and add one or more behaviour to this object. One should avoid using controllers to do some of the following:
    • Manipulate DOM, 
    • Format input, 
    • Filter output, 
    • Share code or state across different controllers
    • Manage the life-cycle of other components (for example, to create service instances)
  • A controller should contain only the business logic needed for a single view. The functionality should rather be moved to services and these services should be injected into the controllers using dependency injection.
  • The recommended way to declare the controller function is to use the array notation such as following because it protects against minification.

Controller instantiation without array notation

var helloApp = angular.module( "helloApp", [] );
helloApp.controller( "HelloController", function($scope){
$scope.name = "Guest";
} );

Controller instantiation with array notation (Recommended way)

var helloApp = angular.module( "helloApp", [] );
helloApp.controller( "HelloController", ['$scope', function($scope){
$scope.name = "Guest";
}]);
  • While writing unit tests for controllers, one of the recommended ways is to inject $rootScope & $controller. Take a look at the sample unit tests on this page: http://hello-angularjs.appspot.com/angularjs-unit-test-code-example-1. The following is the sample code representing injection of $rootScope and $controller objects.
    beforeEach(
    inject(
    function( $rootScope, $controller ){
    scopeMock = $rootScope.$new();
    $controller( 'CompanyCtrl', {$scope: scopeMock} );
    }
    )
    );

Directives

  • One should prefer using the dash-delimited format (e.g. ng-model for ngModel). While working with an HTML validating tool, one could instead use the data-prefixed version (e.g. data-ng-model for ngModel).
  • Prefer using directives via tag name and attributes over comment and class names. Doing so generally makes it easier to determine what directives a given element matches.
  • While creating directives, it is recommended to prefix your own directive names to avoid collisions with future standard.

Template

  • With large templates (HTML content with Angular directives) within an HTML file, it is recommended to break it apart into its own HTML file and load it with the templateUrl option.

Dependency Injection

The preferred way of injecting the dependencies is by passing the dependency to the constructor function rather than using one of the following other ways. In this way, the responsibility of creating the dependency object lies with other objects or function. This is straight forward for those who have worked with one or more dependency injection framework in the past. However, this could be useful information for the beginners. Following are other ways of doing dependency injection in Angular:

  • Create it using the new operator.
  • Look for it in a well-known place, also known as a global singleton.
  • Ask a registry (also known as service registry) for it.

Unit Testing

  • As mentioned above, one should try and avoid using controller methods for DOM manipulation. That would bring views code inside the methods and make it difficult to test.
  • One may want to use Jasmine/Karma combination for doing controller methods testing.
  • Protractor framework can be used for E2E testing, as recommended. Read more on Angular page for E2E testing.

References

  • https://docs.angularjs.org/guide
AngularJS Coding best practices unit test Dependency injection Coding (social sciences)

Published at DZone with permission of Ajitesh Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Dependency Injection
  • Hints for Unit Testing With AssertJ
  • Code Review That Matters: Tips and Best Practices
  • Fighting Climate Change One Line of Code at a Time

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!