The other day, spurred on by Mr. Ward’s Building Salesforce1 Mobile Apps with Visualforce, AngularJS, and Bootstrap, I became curious about whether or not I could mix Remote Actions in with his code, and it turns out I can. And more than that — it turns out to be pretty sweet!
I’ve included a video demo at the bottom of the post and you can install these pages into your developer edition from this unmanaged package. Note that once you install these into your org, you’ll want to add them to your Mobile Navigation in order to see the Salesforce1 #awesomesauce. Code is also on github.
The foundations of Remote Actions are simple. You create an Apex class that performs the operation you want, and then use a @RemoteAction annotation to expose a particular method to the JavaScript Remoting framework.
global class SampleRemoteActionPageController { @RemoteAction global static List myContacts() { return [select id, name, email from Contact Order By LastModifiedDate DESC LIMIT 200]; } }
You then create a simple page that calls that remote action.
<apex:page controller="SampleRemoteActionPageController" docType="html-5.0"> <apex:stylesheet value="//cdn.jsdelivr.net/webjars/bootstrap-sf1/0.1.0-beta.6/css/bootstrap-namespaced.css"/> <apex:includeScript value="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.11/angular.min.js"/> <script> var app = angular.module("ngApp", []); app.controller("ContactCtrl", ["$scope", function($scope) { $scope.contacts = []; $scope.getContacts = function() { Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.SampleRemoteActionPageController.myContacts}', function(result, event) { $scope.contacts = result; $scope.$apply(); }); } }]); </script> <div class="bootstrap" ng-app="ngApp" ng-controller="ContactCtrl" > <h1 align="center">Click The Button</h1> <button ng-click="getContacts()" class="btn btn-lg btn-default btn-block">Get Contacts</button> <p> <ul> <li id="{{current.Id}}" ng-repeat="current in contacts" ng-class-even="'rowEven'">{{current.Name}}</li> </ul> </p> </div> </apex:page>
I love the simplicity and flexibility I’m seeing here.
Just for fun, I also created a demo using the new Remote Objects functionality that’s still in developer preview. It also works well in both the desktop browser and Salesforce1 mobile app. Checkout the video below!
Good post and I really like the idea of mixing angularjs with remote actions. In fact, try it without the invoke, it should still work and is cleaner!
$scope.getContacts = function() {
SampleRemoteActionPageController.myContacts(function(result, event) {
$scope.contacts = result;
$scope.$apply();
});
}
Note, you can also pass arguments to the remote action like this
.myContacts($scope.Arg1, $scope.Arg2, function(result, event) {
or, pass in a complex DTO like this
myContacts($scope.ComplexShape, function(result, event) {
Cool! A simple oage made even simpler! Thx
Hello sir need help. how to do this with angular pagination?