Search code examples
angularjsforce.com

angular js force.com Javascript remoting


I am new to Angular JS and really struggling to get data into my controller from javascript remoting. Has anyone done this before?

Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Forecasting.Users}',
  new Object(),function(result, event){
    return result
  }
);

How on earth do i get the data into the controller :

var forecastingCtrl = function($scope, $q){
    $scope.lengths = function(){return '5'};
    $scope.users = [];
}

EDIT : Following works fine:

fc.service('Users', function($rootScope, $q) {
    this.get = function(){
        var deferred = $q.defer();

            Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Forecasting.Users}',new Object(),function(result, event){
                if(event) {
                     $rootScope.$apply(function() {
                        deferred.resolve(result);
                    });

                } else { 
                    deferred.reject(result);
                }            
            });
            return deferred.promise;

    }

});

function forecastingCtrl($scope, $q, Users){
    $scope.lengths = function(){return '5'};


    var promise = Users.get();
    promise.then(
        function(users){
            $scope.users = users;
        },
        function(reason){
            alert('Failed: ' + reason);
        }
    );    

};

Solution

  • I haven't used javascript remoting (sounds interesting) but what you will probably want to do is to encapsulate your visualforce code inside a service, having a method (most likely a promise) to return your data and inject the service into your controller. The upside of this is that you can unit test your controller by injecting a mock or spy of your data service. The pattern would be very much like how you would use angular's $http and $resource services. Hopefully this gets you on the right track.