Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a php variable to angular

I am building a webapp and I'm using angular for the first time. I tried yesterday to get data from an API but it will not work in Angular cause of cross origin resource restrictions. Lucky I can get the json date over a simple CURL request in PHP.

So here I am now. I have the JSON Data in a PHP Variable and want to use this data in my Angular Application. How can I achieve that? Is there a way to pass the data directly to angular? Or should i create a json file with php and then load it into my funcion? What suggestions do you have?

I want to fill the $scope.posts with the content of the php variable $content.

Here's the php code:

<?php


        /* gets the data from a URL */
        function get_data($url) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
        }

        $returned_content = get_data('http://fingerzeig.ch/api/agenda/list');
        $content = json_decode($returned_content);
        //print_r ($content);

        //Get first title
        //$firstitle = $content[0] -> ID;

        //print_r($firstitle);



        ?>

The Angular code:

//MYAPP

var app = angular.module("MyApp", []);


app.controller("PostsCtrl", function($scope, $http) {
  $http.get(' WHAT SHOULD GO HERE? ').
    success(function(data, status, headers, config) {
     console.log("success!");
     console.log(data);
      $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});
like image 819
elpeyotl Avatar asked Nov 13 '14 20:11

elpeyotl


2 Answers

You could provide and endpoint using apache and php to get this data from your own server:

$http.get('/endpoint', function () { ... });

You could also do something sometimes referred to as 'bootstrapping' data into the DOM. This works fine - I typically do it to ensure the first page load of a single page app doesn't require waiting on initial data. Everything for the first page load is set up on the server and rendered into the page for the app to collect without making further requests:

To do this, you can create a collection on the window or global scope like this:

window.myPostData = "<?php echo $data; >";

Then later in your app, you can typically expect the window object (or any global variable) to be available in the browser at all times so it'll be accessible like this:

app.controller("PostsCtrl", function($scope) {
    var posts = window.myPostData;
});

However, you probably want to be able to access fresh data as well, so you'd probably try something like this:

// If $data is empty, set myPostData to false.
window.myPostData = <?php echo empty($data) ? 'false' : $data; >;

...

app.controller("PostsCtrl", function($scope, $http) {
    var posts = window.myPostData;

    // Set myPostData to false so future use of this controller during this
    // request will fetch fresh posts.
    window.myPostData = false;

    // Now if we didn't bootstrap any posts, or we've already used them, get them
    // fresh from the server.
    if (!posts) {
        $http.get('/endpoint', function() {
            ...
        });
    }
});

Mind you, if you don't have the understanding of how to set up an endpoint using apache and php, you will want to stick with only bootstrapping the data onto the window or a global variable. It's not ideal, but it would work.

like image 93
Steve Adams Avatar answered Oct 18 '22 00:10

Steve Adams


Thank you everybody for your help. It is working and the solution was very simple.

I created a variable in Javascript which gets the returned content of PHP.

var thedata = <?php echo $returned_content;?>;

Then i put this variable in my angular app file:

//MYAPP

var app = angular.module("MyApp", []);

app.controller("PostsCtrl", function($scope) {
  $scope.posts = thedata;
  console.log(thedata);
});

I can access this data now in my ng-repeat.

<body ng-app="MyApp">
  <div ng-controller="PostsCtrl">
    <ul ng-repeat="post in posts">
      <li>{{post.ID}}</li>
    </ul>
  </div>
</body>

It works sweet! Very simple solution.

like image 4
elpeyotl Avatar answered Oct 18 '22 01:10

elpeyotl