Skip to main content

Angular JS with Salesforce Remote Actions

Using Angular JS with Remote Actions

Nowadays Angular JS is a great front end framework to bind DOM objects easily and do many more things in the DOM. Here I'm going to describe how to use Angular with visual force and apex remote actions. So we can add angular code in the visual force page itself or we can add angular code to the static resource. As per the my understanding , If we use angular code in the visual force page itself it will break the single page application concept. Because when rendering a new visual force page we have to create one angular application for each visual force page. So in this post I'm going to use static resource to write angular code. And also I'm going to use welkin suite for as the IDE. Because from welkin suite we can modify the static resource bundle (But currently we cannot add js files for partial pages to static resource , only thing what we can do is modify the bundle , but it is great because we can compare the modifications what we have done) and also welkin suite is really familiar to me because I'm from .NET background.  When we using static resource we have to consider one things of the sales force governor limit. That is static resource is limited to 5 MB. If you using more that 5MB for the static resource bundle you have to separate the bundle.


You can download welkin suite from https://welkinsuite.com/downloads/

Create Static resource Angular Bundle 

Hope you have some knowledge of the Angular developments.And I'm going to use UI route for the routing mechanism for the app. Initially you have to create the folder structure for the angular static resource bundle as below. Here I'm using two controllers (firstController.js) and one service (firstService.js) and two partial html (firstView.html , secondView.html) pages and app.js file. So create this folder structure with the empty js and empty html files and add it to the static resource.


app

- controllers

      - firstController.js

- services

      -firstService.js

- views

      -firstView.html

      -secondView.html

app.js 

 

If you going to use welkin , create a new project by giving your credentials and security token. Or else you can you MavensMate or another tool to edit static resource. 

 

  •  Now you need to create a visual force page to make the root page container for the angular app. So go and create a visual force page . I have created as AngularTest.page .

  • Then create a apex class to create the remote action. I have created as AngularRemoteClass.

 

Here I'm going to demonstrate an really simple angular application in order to call to a remote action. So I have wrote a RemoteAction method as 'angularRemoteFunction'. It will return and Boolean true value once you give any name. According to the requirement you can make the modifications to the RemoteAction. Here I will keep it as a very simple.

 

 public class AngularRemoteClass {

    @RemoteAction
    public static Boolean angularRemoteFunction(String name) {
             
        return true;


    }


}

 

  • Below I have added apex page content. Here I have added angular.js file and angular ui route file from the cdn. If you like you can add those angular files to the static resource.  I have create angular app as MyApp. And I have added  <ui-view></ui-view> tags to add html partials dynamically from angular.

  • And also here I have added SitePrefix javascript variable, because from the static resource we cannot directly call to the apex global variables. So I have added it to the js variable and then I can call to the SitePrefix from the static resource js files. This SitePrefix will use in the angular bundle. (AngularApp is the static resource bundle name)

    var SitePrefix="{!URLFOR($Resource.AngularApp)}/app/" ;

  • After the ui view tag I have referenced to the app.js file , firstController.js and firstService.js file from the static resource.

 

 

<apex:page controller="AngularRemoteClass" showheader="false" sidebar="false" doctype="html-5.0" standardstylesheets="false">
    <html lang="en">

    <head title="MyApp">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
        <script type="text/javascript">

          var SitePrefix="{!URLFOR($Resource.AngularApp)}/app/";

        </script>
    </head>
       <body ng-app="MyApp">

        <ui-view></ui-view>
        <!-- Add JS Files HERE -->
        <script src="{!URLFOR($Resource.AngularApp)}/app/app.js"></script>
        <script src="{!URLFOR($Resource.AngularApp)}/app/controllers/firstController.js"></script>
        <script src="{!URLFOR($Resource.AngularApp)}/app/services/firstService.js"></script>
    </body>
</html>

</apex:page> 

 

  • app.js file

I have used ui-route for the routing , therefore I have injected $stateProvider to the config.

 
 (function () {
    'use strict';

    angular.module('MyApp', [
        'ui.router',
        'MyApp.services',
        'MyApp.controllers'
   
    ])
        .config(function ($stateProvider, $urlRouterProvider) {

            $urlRouterProvider.otherwise('/default');

            $stateProvider
                .state('default', {
                    url: '/default',
                    views: {
                        '': {
                            templateUrl: SitePrefix + 'views/firstView.html',
                            controller: 'firstController'
                        }
                    }
                })
        })

      
    angular.module('MyApp.services', []);
    angular.module('MyApp.controllers', []);
}());

  • firstController.js

In here I have injected myFirstService factory method to call Apex Remote Action.

 

(function(){

    'use strict';

    angular.module('MyApp.controllers').
        controller('firstController', ['$scope' , '$rootScope' , 'myFirstService' , function ($scope , $rootScope , myFirstService )     {
      
             myFirstService.authenticateUser({ name : 'prasad' } ,
          
                //success calla back
                function(data) {
                    console.log(data);
                },
              
                //error call back
                function(data) {
              
                    console.log(data);

                });
      
        }]);

}());

 

 

  • firstService.js

 If you using namespace so you have to use that namespace when you calling to the Remote Action. 'prasadRevenueS' is my namespace.

(function(){

    'use strict'

    angular.module('MyApp.services')

        .factory('myFirstService' , ['$rootScope' , '$q' , '$http' , function ($rootScope , $q ,$http ){

        

            var myAPI = {};

              myAPI.authenticateUser = function (param, successCallBack, errCallBack) {

                  var promise = $q.defer().promise;

                   Visualforce.remoting.Manager.invokeAction('prasadRevenueS.AngularRemoteClass.angularRemoteFunction', param,

                    function(result, event){

                     if (event.status) {

                        console.log('#### Result ####');

                        console.log(result);

                        $rootScope.$apply(function() {

                            promise.then(successCallBack(result));

                        });

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

                      errCallBack(event);

                     } else {

                      errCallBack(event);

                     }

                    },

                    {escape: false}

                   );

                  return promise;

              };

                

              return myAPI;

        

        }]);

}());

 

 

If everything when well you call see the true result from your browser log. Please note this post is only to understand how to make the flow with angular and remote actions. Please share your ideas on this.

 

Thanks,

Prasad 

Comments

Popular posts from this blog

Integrate .NET console application with Salesforce Rest API

According to the integration perspective in Salesforce there are several APIs to integrate with external systems. As an example there are REST API, SOAP API, Bulk API, Tooling API and Streaming API. Here I will focusing for Rest API. I have created a different post which will describing the integration with Salesforce Soap API. You can find it from  here . And for the Tooling API you can find it from  here . 1st of all you need to create a connected app in Salesforce in order to make the bridge to integrate with console app.  A connected app integrates an external application with Salesforce using APIs. Connected apps use standard SAML and OAuth protocols to authenticate, provide single sign-on, and provide tokens for use with Salesforce APIs. So I have created a separate post which will describe how to create a connected app to get consumer id and consumer secret. Please follow  this   post to get consumer id and consumer secret. After you...

How to automate testing using Selenium and C#

Hi All, today I’m going to explain about Selenium which is a open source automation tool and how to utilize it with C#. As you know automation tools save our time in terms of testing a software product. If we are doing some regression testings automation tools doing a great job in terms of saving the time. So I’m going to explain a very simple example for using Selenium from C#. We can divide selenium as two entities. One is Selenium IDE as a web browser extension. And the other one is Selenium Web Driver. So I’m going to talk about the selenium web driver which is using for web based testings from C# code. Basically Selenium Web driver will open the browser and doing the actions as we instructing in the C#code. Firstly you need to install visual studio. For my case I have installed visual studio community version which is a free version of Microsoft. Then you need to create a project by navigating to File -> New -> Project. And give a name for the project and click ok...

How to connect Salesforce with .NET console application using SOAP api

This article mainly focusing on the basics about the integration with Salesforce and .NET console application via Salesforce SOAP api. So I would prefer to start it form Salesforce. :) . And I think it would be easy if I continuing with Steps so the viewers can go through the steps easily. 1st Step : Navigating to Enterprise WSDL from Salesforce. You will be able to generate WSDL in Salesforce by Navigating to Setup -> Integrations -> API.  Here you will be able to see different apis which will be generating for different purposes. In order to do this you need to log in as an system administrator or as a user who has the “Modify All Data” permission. You will be able to see below APis. Enterprise WSDL Partner WSDL Apex WSDL Metadata WSDL Tooling WSDL Generate Tooling WSDL Delegated Authentication WSDL Client Certificate Enterprise Package Version Settings Partner Package Version Settings We are focusing Enterprise WDSL in order to integrate with .NET and you want t...