6

I have a static resource that contains an angular.js module. Now i want to call, in this static resource, a javascript function that is located in a Visualforce Page.

Is it possible to use the Visualforce.remoting.Manager.invokeAction? If not, could one resolve this issue?

10

Its definitely doable .You will need to use window global object to resolve all merge fields and then use the object in your static resource .

Here is a simple hello world example

<html lang="en">
<head>
 <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>Javascript Tips</title>
    <script>
        window.configSettings = {
            user:{
                id : '{!$User.Id}',
                firstName : '{!$User.FirstName}',
                lastName : '{!$User.LastName}',
                uiThemeDisplayed : '{!$User.uiThemeDisplayed}', 
            },
          remoteActions: {
                helloWorld : '{!$RemoteAction.TestController.helloWorld}',
            }
        }
    </script>
   <apex:includeScript value="{!URLFOR($Resource.MyJavascriptFile)}"/>
  </head>
  <body>
  <div> ....</div>
</body>

apex class

public with sharing class TestController {  
 @ReadOnly    
 @RemoteAction    
 public static String helloWorld() { 
   return 'hello word' ;  
 } 
}

The Static Resource Script

(function (window) {     
  Visualforce.remoting.Manager.invokeAction(
  window.configSettings.helloWorld,
  function(result, event) {
    if (event.status) {
     console.log(result);
    } else {
      //handleReturnError(event);
    }
   },      
    {buffer: true, escape: true}
  );
})(window);
3
  • 2
    Excellent answer. for us non java folks this helps bridge a gap. Would make an excellent blog post....... – Eric Mar 3 '17 at 16:15
  • 1
    Ah nice, had wrote something similar, not better than yours though (still learning the best practices). With that it doesn't pollute window object directly. – Raul Mar 3 '17 at 16:37
  • 1
    @RahulSharma I loved the module pattern .Its great.The thing about Javascript is its changing so much .This is ES5 way of doing it .In ES6 we have classes and other ways to handle this polluting issues . – Mohith Shrivastava Mar 3 '17 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.