Angular JS Best Practices

1. Create one directive per file
2. Create one controller per file
3. Create one service per file
4. Have only routes and general usablility code on app.js
5. Don’t ever user $rootScope, rather make use of Angular services
6. Prefer Restangular for complex API calls, $http for simple API calls, avoid $resource.
7. Don’t use {{ }} on view files, rather use either ng-bind (or) data-prefixed version
8. Use native for loops than angular.forEach
9. Only for a small storage purpose go for $cookieStore, for storing medium and large informations use $localStorage or $sessionStorage according to the need

NAMING CONVENTIONS

UpperCamelCase for Controllers and constructor Services, lowerCamelCase everywhere else.

Controllers

The naming of the controller is done using the controller’s functionality (for example shopping cart, homepage, admin panel) and the substring Ctrl in the end. The controllers are named UpperCamelCase (HomePageCtrl, ShoppingCartCtrl, AdminPanelCtrl, etc.).

Directives

Name your directives with lowerCamelCase.

Filters

Name your filters with lowerCamelCase.

Services

Use camelCase to name your services.

  • UpperCamelCase (PascalCase) for naming your services, used as constructor functions
  • lowerCamelCase for all other services.

Note that Services always return singletons. Unless you create a special service to return a newed object each time it gets called–in this case, and only in this case should you use PascalCase naming.

DIRECTORY STRUCTURE

root-app-folder
├── index.html
├── scripts
   ├── controllers
      └── main.js
      └── ...
   ├── directives
      └── myDirective.js
      └── ...
   ├── filters
      └── myFilter.js
      └── ...
   ├── services
      └── myService.js
      └── ...
   ├── vendor
      ├── angular.js
      ├── angular.min.js
      ├── es5-shim.min.js
      └── json3.min.js
   └── app.js
├── styles
   └── ...
└── views
    ├── main.html
    └── ...


THINGS TO REMEMBER

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";
}
  • 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 defined using “.controller” method (Recommended way)

var helloApp = angular.module( "helloApp", [] ); 
helloApp.controller( "HelloController", 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.

Also Refer : https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

 

 
Advertisements

Angular JS Dynamic searching for a collection of objects, with min & max range (i.e., persons with age from 18 to 60)

View:-

<div ng-repeat=”car in cars | filter: byRange(fieldname, min_value, max_value” >

…….

……

</div>

Controller:-

$scope.byRange = function (fieldName, minValue, maxValue) {
if (minValue === undefined) minValue = Number.MIN_VALUE;
if (maxValue === undefined) maxValue = Number.MAX_VALUE;

return function predicateFunc(item) {
return minValue <= item[fieldName] && item[fieldName] <= maxValue;
};
};

That’s it just pass in the field name, min_value and max_value to the ‘byRange’ function and get the dynamic searching for collection of objects.

Angular JS implementation with Rails 4

Step 1 : Create rails app using rails new employee_details
Step 2 : Remove turbolinks gem from gemfile and add ‘pg’ gem for postgres. Set the rails version to 4.1.2 (Turbolinks may not work with angular js)
Step 3 : Run bundle install
Step 4 : Change database.yml to use postgres
development:
adapter: postgresql
encoding: unicode
database: employee_details
username: postgres
password: root
pool: 100
Step 5 : Create the model
rails g model EmployeeDetail employee_id:integer employee_name:string expertise:string experience:integer education:string mobile:string address:text gender:boolean
Step 6 : Run rake db:create and rake db:migrate
Step 7 : Create a controller
rails g controller employee_details
class EmployeeDetailsController < ApplicationController
def index
end
end
Step 8 : Create a view file for employee_details
<div>
<h1>Ruby on Rails Rocks</h1>
</div>
Step 9 : Add routes for index page
root ’employee_details#index’
Step 10 : Change layout file, remove turbolinks, add ng-app with the app name and point angular javascripts
<!DOCTYPE html>
<html ng-app=”EmployeeDetails”>
<head>
<title>Employee Details</title>
<%= stylesheet_link_tag ‘application’, media: ‘all’ %>
<%= csrf_meta_tags %>
</head>
<body>
<header>
Angular
</header>

<%= yield %>
<script src=”//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js”></script>
<script src=”//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular-resource.min.js”></script>
<%= javascript_include_tag “application” %>

</body>
</html>
Step 11 : change assets/javascripts/application.js
//
//= require app
//= require_tree ./../angular
Step 12 : Define app which we referred above in app.js.coffee
window.App = angular.module(‘EmployeeDetails’, [‘ngResource’])
Step 13 : Define custom routes
EmployeeDetails::Application.routes.draw do
root ’employee_details#index’
end
Step 14 : Create directories as below
assets/angular
assets/angular/controllers
assets/angular/services
assets/angular/directives
Running the app now should display ‘Ruby on Rails Rocks’
Step 15 : Change the index.html to below
<div ng-controller=”EmployeeDetailsCtrl”>
<h1>Message: {{title}}</h1>
</div>
Step 16 : Now create the angular controller (inside assets/angular/controllers/employeedetailsCtrl.js.coffee) referred above and assign title
App.controller ‘EmployeeDetailsCtrl’, [‘$scope’, ($scope) ->
$scope.title = “Ruby on Rails Always Rocks!”
]
Restart the server. Running the app now should display ‘Ruby on Rails Always Rocks’
Step 17 : Change the index method of controller and render json
class EmployeeDetailsController < ApplicationController
def index
render json: EmployeeDetail.all
end
end
Step 18 : Generate few records using seed
#Emp ID, Emp Name, Expertise, Experience, Education, Mobile, Address, Gender
employees = EmployeeDetail.all.count
if employees == 0
employee_id = [101,102,103,104,105]
employee_name = [“Arun”, “Kumar”, “Raja”, “Karthik”, “Surya”]
expertise = [“RubyOnRails”, “English Literature”, “PhP”, “Admin”, “Java”]
experience = [5,4,3,4,5]
education = [“M.C.A”, “M.A”, “B.E”, “B.E”, “B.E”]
mobile = [“9987656478”, “9878965437”,”9786587987″, “9879547897”, “9876096543”]
address = [“Chennai”, “Madurai”, “US”, “Cuddalore”, “Trivandrum”]
gender = [0,1,1,0,0]
for i in 0..4
EmployeeDetail.create(
employee_id: employee_id[i], employee_name: employee_name[i],
expertise: expertise[i], experience: experience[i],
education: education[i], mobile: mobile[i],
address: address[i], gender: gender[i]
)
end
end
Step 19 : Run rake db:seed
Now go and run the app, you should see the records in JSON format.
Step 20 : Create the home controller (we will be using this controller for angular implementation)
class HomeController < ApplicationController
def index
end
end
Step 21 : Apply root to home controller index method and create api routes for angular
scope :api do
get “/employee_details(.:format)” => “employee_details#index”
get “/employee_details/:id(.:format)” => “employee_details#show”
end
root ‘home#index’
Step 22 : Get the records on angular controller
App.controller ‘EmployeeDetailsCtrl’, [‘$scope’, ‘EmployeeDetail’, ($scope, EmployeeDetail) ->
$scope.showEmployeeDetail = null
$scope.selectedRow = null

$scope.employee_details = EmployeeDetail.query ->
$scope.showEmployeeDetail = $scope.employee_details[0]
$scope.selectedRow = 0

$scope.showEmployeeDetail = (employee, row) ->
$scope.showEmployeeDetail = employee
$scope.selectedRow = row
]
Step 23 : Create the service for api
App.factory ‘EmployeeDetail’, [‘$resource’, ($resource) ->
$resource ‘/api/employee_details/:id’, id: ‘@id’
]

Step 24 : Now change the view file for listing employees (app/views/home/index.html.erb)
<div ng-controller=”EmployeeDetailsCtrl”>
<ul>
<h1>{{title}}</h1>
<li ng-repeat=”employee in employee_details”>
<h3>{{employee.employee_id}} <small>({{employee.employee_name}})</small></h3>
</li>
</ul>
<div ng-show=”showEmployeeDetail”>
<h2>{{showEmployeeDetail.employee_id}}</h2>
<p>{{showEmployeeDetail.employee_name}}</p>
<p>
Expertise : {{showEmployeeDetail.expertise}}
</p>
</div>
</div>

 

Restart the server. Executing the application at http://localhost:3000 will now display the list of employees and the information of first employee.