[SalesForce] Call Javascript function on visualforce page from static resource

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?

Best Answer

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);