Search code examples
javascriptangularjsopencpu

Using AngularJS $scope within OpenCPU


I have an alright knowledge of angularjs but I am more of a R programmer and I have therefore being experimenting with OpenCPU js library.

One thing I can't get my head around is why I can't assign the output from a simple API request to the public OpenCPU server, rnorm(n = 2) function, to an angular $scope. What baffles me is that I can use jquery to assign the returned json via ID for example.

From what I understand it is best practice not to mix jquery into the angular controller. Am I right in thinking this?

Working with Jquery

app.controller('rCtrl', function($scope){

  req = ocpu.rpc('rnorm',{
    n : 2
  }, function(output){$('#output').text(output)});
})

Not Working $scope

app.controller('rCtrl', function($scope){

  req = ocpu.rpc('rnorm',{
    n : 2
  }, function(output){$scope.normalValues = output)});
})

Solution

  • Since you are using a non-angular tool you are assigning $scope.normalValues outside of the Angular digest loop. Use a $scope.apply() to fix this:

    app.controller('rCtrl', function($scope){
    
      req = ocpu.rpc('rnorm',{
        n : 2
      }, function(output){
         $scope.$apply(function(){
             $scope.normalValues = output;
         });
      )});
    });
    

    You can also just call $scope.$apply() right after you set your scope value but I personally like the callback syntax since it makes it easier to see why you use it.