最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing a php variable to angular - Stack Overflow

programmeradmin7浏览0评论

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('');
        $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
    });
});

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
    });
});
Share Improve this question edited Nov 13, 2014 at 21:35 Bijan 8,59620 gold badges102 silver badges160 bronze badges asked Nov 13, 2014 at 20:34 elpeyotlelpeyotl 3721 gold badge3 silver badges15 bronze badges 2
  • Do you have control over the API in order to allow access to your Angular app? – Steve Adams Commented Nov 13, 2014 at 20:38
  • @SteveAdams no i do not have control unfortunately. So I have the data here on my website already in this php variable. I can echo it out and everything. But how to work with it in my angular app? – elpeyotl Commented Nov 13, 2014 at 20:43
Add a ment  | 

4 Answers 4

Reset to default 9

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.

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.

You could just force it on to the scope like this, not sure if it is best practice but ya... Or you could have your angular controller call to a php function in an

$http.get('func').then(function(data) {
//do stuff
});

or just shove it on scope

<input ng-model="myContent" value="<?php echo $returned_content?>"/>

Since you're already getting JSON data, just output the JSON data. No need to do json_decode.

So just echo $returned_content

Edit:

The part where you have $http.get(' WHAT SHOULD GO HERE? ') in your Angular code should point to the relative URL of the PHP page. e.g. If your PHP page is accessed at http://server./webapp/get_data.php then your angular would be $http.get('/webapp/get_data.php')

发布评论

评论列表(0)

  1. 暂无评论