将php变量传递给angular

elp*_*otl 5 javascript php json curl angularjs

我正在构建一个webapp,我第一次使用角度.我昨天尝试从API获取数据,但它不适用于Angular原因的跨源资源限制.幸运的是,我可以通过PHP中的简单CURL请求获取json日期.

我现在在这里.我在PHP变量中有JSON数据,并希望在我的Angular应用程序中使用这些数据.我怎样才能做到这一点?有没有办法将数据直接传递给角度?或者我应该用PHP创建一个json文件,然后将其加载到我的函数中?你有什么建议?

我想用php变量$ content的内容填充$ scope.posts.

这是php代码:

<?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);



        ?>
Run Code Online (Sandbox Code Playgroud)

角度代码:

//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
    });
});
Run Code Online (Sandbox Code Playgroud)

Ste*_*ams 9

您可以使用apache和php提供和端点从您自己的服务器获取此数据:

$http.get('/endpoint', function () { ... });
Run Code Online (Sandbox Code Playgroud)

您还可以在DOM中执行有时称为"引导"数据的操作.这很好 - 我通常这样做是为了确保单个页面应用程序的第一页加载不需要等待初始数据.第一页加载的所有内容都在服务器上设置并呈现到页面中,供应用程序收集而无需进一步请求:

为此,您可以在窗口或全局范围上创建一个集合,如下所示:

window.myPostData = "<?php echo $data; >";
Run Code Online (Sandbox Code Playgroud)

然后在您的应用程序中,您通常可以期望窗口对象(或任何全局变量)始终在浏览器中可用,因此它可以像这样访问:

app.controller("PostsCtrl", function($scope) {
    var posts = window.myPostData;
});
Run Code Online (Sandbox Code Playgroud)

但是,您可能希望能够访问新数据,因此您可能会尝试这样的事情:

// 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() {
            ...
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,如果您不了解如何使用apache和php设置端点,您将只想坚持将数据引导到窗口或全局变量上.这不是理想的,但它会起作用.