Published on
September 28, 2016

Setup a consultation

Salesforce With Angular JS

Angular JS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly.

There are a couple of Advantages of  Angular JS:

a. Angular JS provides capability to create Single Page Application in a very clean and maintainable way.b. It provides data binding capability to HTML thus giving the user a rich and responsive experiencec. Angular JS code is unit testable.d. Angular JS uses dependency injection and make use of separation of concerns.e. It provides reusable components.f. With Angular JS, developer write less code and get more functionality.g. In Angular JS, views are pure html pages, and controllers written in JavaScript do the business processing.

On top of everything, Angular JS applications can run on all major browsers and smartphones including Android and iOS based phones/tablets.

The AngularJS Components:

The AngularJS framework can be divided into the following three major parts −

  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.

How to use Angular JS in Visualforce?

JavaScript gained momentum because of its success in frameworks and due to a higher demand of visually appealing, mobile-friendly single page applications. In Visualforce, the backend is not that flexible but the frontend is. So a framework like AngularJS is greatly preferred to create structured applications having excellent response times. Considering that each Visualforce app revolves around the four functions of create, read, update, and delete on Salesforce data, there are three distinct approaches to binding the Salesforce data to Visualforce controllers.

  1. Creating and using JavaScript Remote objects with Visualforce.
  2. Using Force TK libraries along with Angular JS libraries.
  3. Using JSON.

Visualforce page is lucid because you can start coding without opening or uploading multiple files to a server. We will proceed further with an example, in which we are going to fetch a list of Contacts from Salesforce and add a search function exhibiting two-way data binding

We developed a sample application to Displaying Object Records using AngularJS with Search and Paging functionality.

Source Code for VF Page

<apex:page docType="html-5.0" standardStylesheets="false" sidebar="false" showHeader="false" applyHtmlTag="false"><html>    <c:ComponentName sobjectName="Account" fieldCsv="Name, Type, Phone, BillingCity, BillingPostalCode" searchable="true"/>      </html></apex:page>

Note :

      ComponentName - Name of the component

      sobjectName   - Name of the object

      fieldCsv      - Fields to display in the page

      Searchable    - yes or no.

Source Code for VF Component

Need to use below dependencies of Javascript and Css

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" /><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/><link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/><apex:includeScript value="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"/><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script><script src="{!URLFOR($Resource.AngularDataTable,'app.js')}"></script><script src="{!URLFOR($Resource.AngularDataTable,'controllers.js')}"></script><script src="{!URLFOR($Resource.AngularDataTable,'services.js')}"></script><script src="{!URLFOR($Resource.AngularDataTable,'directives.js')}"></script>

App.js

angular.module is a global place for creating, registering and retrieving Angular modules

// 'dataTable' is the name of this angular module example (also set in a <body> attribute in index.html)

// the 2nd parameter is an array of 'requires'

// 'dataTable.services' is found in services.js

// 'dataTable.controllers' is found in controllers.js

// 'dataTable.directives' is found in directives.js

'use strict';

var sortingOrder = 'name';

angular.module('communities', ['ngRoute', 'communities.controllers', 'communities.services','communities.directives'])

//.config(['$routeProvider', '$stateProvider', function($routeProvider, $stateProvider) {

.config(['$routeProvider', function($routeProvider) {

$routeProvider.when('/list', {templateUrl: '/apex/VFPagename', controller: 'userdefinedcontrolname'});

$routeProvider.when('/detail/:id', {templateUrl: '/apex/VFPagename', controller: 'userdefinedcontrolname1l'});

$routeProvider.otherwise({redirectTo: '/list'});

}]);

Controller.js

Usefult to Get All the Records to display in a tabular format, using Promise / Defer

//AngularJS variables used in controller.js

$scope.sortingOrder = sortingOrder; //sorting

$scope.reverse = false;

$scope.filteredItems = [];//filter based on search criteria

$scope.itemsPerPage = 5; //Records to display per page

$scope.pagedItems = [];//Records in Page

$scope.currentPage = 0;//Current page number

Services.js

Useful to return records based on object and field input provided by component parameters

AngularTableController.getAllRecords(sobjectName, fieldSetName,fieldsToShow, function(result,event){

if(event.type == 'exception'){

alert(event.message);

deferred.fail(event.message);

}else{

records = result;

console.log(records);

$rootScope.$apply(function(){

deferred.resolve(records);

});

}

});

After Binding Controller to Body of Page<div class="container" ng-app="communities"><div ng-controller="UserCtrlName"><div class="row"><div class="panel panel-success"><div class="panel-heading"><div class="row"><div class="col-xs-6 text-left pull-left"><h3 class="panel-title">{!sobjectName} List</h3></div><div class="col-xs-6 text-right pull-right"><label>Search: <input type="text" ng-model="query" ng-change="search()" /></label></div></div></div><div class="panel-body"><table class="table table-striped table-condensed table-hover"><thead><tr><th>Action</th><apex:repeat value="{!fields}" var="fld"><th class="{!fld}">{!fld}&nbsp;<a ng-click="sort_by('{!fld}')"><i class="icon-sort"></i></a></th></apex:repeat></tr></thead><tbody><tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse"><td><a href="#/detail/{{item.Id}}">Open</a></td><apex:repeat value="{!fields}" var="fld"><td>{{item['{!fld}']}}</td></apex:repeat></tr></tbody><tfoot><td colspan="6"><div ><ul class="pagination pagination-large pull-left"><li ng-class="{disabled: currentPage == 0}"><a ng-click="prevPage()">Prev</a></li><li ng-repeat="n in range(pagedItems.length)"ng-class="{active: n == currentPage}"ng-click="setPage()"><a ng-bind="n + 1">1</a></li><li ng-class="{disabled: currentPage == pagedItems.length - 1}"><a ng-click="nextPage()">Next</a></li></ul></div></td></tfoot></table></div></div></div></div></div>

User Interface for our application is as below.

Salesforce with Angular JS

After Search

Salesforce with Angular JS1

Conclusion :  If we want to implement Single Page Applications with rich and responsive experience, Angular JS is definitely a very good option.