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

Exploring the Marvels of Salesforce Marketing Cloud: Unleashing the Power of Marketing Automations

Salesforce Marketing Cloud is a comprehensive marketing automation platform offered by Salesforce, a leading customer relationship management (CRM) company. It is designed to help businesses manage and optimize their marketing efforts across various channels and touchpoints. The platform enables organizations to create, execute, and analyze marketing campaigns to engage with their target audiences more effectively and drive better results. Key features and capabilities of Salesforce Marketing Cloud include: Email Marketing: Users can create and send personalized email campaigns to segmented audiences, track email performance metrics, and automate email workflows to nurture leads and build customer relationships. Journey Builder: This tool allows marketers to design and automate customer journeys across multiple channels such as email, mobile, social media, and advertising. It helps create personalized experiences based on customer behavior and interactions. Social Media Marketing: Sale

Salesforce Metadata API

In this post I'm going the cover basics in the Metadata API and how it can connect with a .net console application. Then after I will show you how to create a custom object and create fields by using the metadata api from the console app. What is Salesforce Metadata API There are many things can be done from the metadata api. you can create Objects,Fields,Validation,Workflows, Profiles, Reports for a particular client organization just by running the piece of code so that you need not do all the customization settings manually which will consume time if you have to do that several times for different clients for the same configuration settings. You can also take the backup of your organization customization settings just by fetching the metadata WSDL from your Salesforce org. You can read, create, update, delete following components in a Salesforce organization. Custom Objects/Fields. Visualforce pages. Page Layouts. Validation rules. Apex. Workflows. Approval processe

Salesforce REST API

This post describe about the salesforce rest api and using salesforce rest api . Salesforce implements the OAuth to authenticate soap and rest calls with the client. So I will describe with the simple steps, how to create salesforce app that expose outside to authenticate and call rest methods. First you need to create a salesforce developer account if you don't have an developer account or sandbox account. If you don't have an developer account go with the following link and create an account. It's free.   https://developer.salesforce.com/signup . Once you create the developer account go to https://login.salesforce.com/ and login with your credentials.     Navigate to setup and type app and you will be able to find Apps section and click the link. So now you will be able to find Connected Apps section and click New. What we doing here is creating a connected app and that app will exposing to outside to authenticate and call rest api calls. So you can insert C