Satheesh Panduga
Satheesh Panduga

Reputation: 818

How to call Angularjs controller function outside the controller in an Ajax call

Am trying to call Angularjs function outside the controller component like the below :

   <script type="text/javascript">
        function saveprof() {
            $('.spinner').show();
            $.ajax({
                type: "POST",
                url: "saveprof",
                enctype: 'multipart/form-data',
                async: true,
                data: {
                    'rinput_Aj': JSON.stringify(angular.element(document.getElementById('rdExampleApp')).scope().$func()),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                    window.location.href = 'myprofile';
                    window.location('myprofile');
                    $('.spinner').fadeOut();
                }
            });
        }
</script>

Here is the angularjs controller code :

 <script>
    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdPlotCtrl', function ($scope) {
        $scope.dataset = {
         "d0": { "id": 0, "name": "Housing", "value": 18 },
         "d1": { "id": 1, "name": "Travel", "value": 31.08 },
         "d2": { "id": 2, "name": "Restaurant", "value": 64 },
         "d3": { "id": 3, "name": "Bank", "value": 3 },
         "d4": { "id": 4, "name": "Movies", "value": 10 }
          };

          $scope.func = function func() {
                 var jdata = $scope.dataset;
                 return jdata;
            }
    });

   </script>

It throws an error Uncaught TypeError: Cannot read property '$func' of undefined

EDIT: After the suggestions, I converted my jquery ajax call to $http function in Angularjs.. But it does nothing.. No error in console :(

Here is how am invoking the $http service function

   <body ng-controller="rdCtrl">
        <a ng-click="saveprof()">Save</a>  

   <script>
    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdCtrl', function ($scope) {
        $scope.dataset = {
     "d0": { "id": 0, "name": "Housing", "value": 18 },
     "d1": { "id": 1, "name": "Travel", "value": 31.08 },
     "d2": { "id": 2, "name": "Restaurant", "value": 64 },
     "d3": { "id": 3, "name": "Bank", "value": 3 },
     "d4": { "id": 4, "name": "Movies", "value": 10 }
      };

      $scope.func = function func() {
             var jdata = $scope.dataset;
             return jdata;
        }, function ($scope, $http) {
        $scope.saveprof = function () {
            //show spinner        
            $('.spinner').show();
            $http.post('saveprof', {
                data: { 'data': JSON.stringify($scope.dataset) }
            })
                      .success(function (data) {
                          if (data == "null") {
                              //your code if return data empty 
                          } else {
                              //your code if return data not empty 
                              $('#message').html(data);
                          }
                          //hide spinner
                          $('.spinner').fadeOut();
                      })
                      .error(function (data, status, headers, config) {
                          console.log('error' + status);
                          //hide spinner in case of error
                          $('.spinner').fadeOut();
                      })
        }
    }
    );
</script>
</body>

What am I missing?

Upvotes: 1

Views: 969

Answers (1)

Theo Itzaris
Theo Itzaris

Reputation: 4681

in order to run XMLHttpRequest requests to the server you have many options in angularjs, you dont have to mess with simple javascript and call angular scope to get variables and functions. you can do that either with $http or with services(leave it for now).

i am going to show how you can make the request with $http in native angular.

  1. first of all you have to import the $http module on the declaration of your controller, like this :

    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdPlotCtrl', function ($scope,$http) {...});
    
  2. into you controller you create the json object as you do it and then do the request like this:

      //show spinner        
     $('.spinner').show();        
     $http.post('dal/addEventHalls.php', {
         data: {'data': $scope.datase}
           })
               .success(function (data) {
                  if (data == "null") {
                     //your code if return data empty 
                  } else {
                      //your code if return data not empty 
                  }
                  //hide spinner
                  $('.spinner').fadeOut();
              })
               .error(function (data, status, headers, config) {
                  console.log('error' + status);
                   //hide spinner in case of error
                  $('.spinner').fadeOut();
               })
    
  3. as you can see we dont use url parameter but we pass the url directly into post() function. the data parameter is there to put whatever data you would like to send to the server.

hope helps good luck.

UPDATE

  1. personally i dont stringify the data parameters.i pass them like json object
  2. into php file , in order to get the data , try this:

    $params = json_decode(file_get_contents('php://input'), true); //read values from angular factory-service

Upvotes: 4

Related Questions