将PHP变量传递给AngularJS,并在脚本中使用它来填充列表


Pass PHP variable to AngularJS and use it to populate a list in the script

我有一个搜索表单,我想从数据库动态。搜索表单依赖于外部的AngularJS脚本来存储数据。

    angular.module('sortApp', [])
    .controller('mainController', function($scope) {
      $scope.sortType     = 'name'; // set the default sort type
      $scope.sortReverse  = false;  // set the default sort order
      // create the list of sushi rolls 
      $scope.engineers = [
        { engineer: 'Mark Smith', team: 'Team 1'  },
        { engineer: 'Sean Barry', team: 'Team 2'  },
        { engineer: 'Ben Matthews', team: 'Team 3'  },
        { engineer: 'Jayson Balls', team: 'Team 4' },
        { engineer: 'Dolton Tims', team: 'Team 5' }
  ];
});

这是脚本代码。逻辑相当简单,我将使用循环来遍历SQL查询的所有结果,将其存储在PHP变量中,并将该变量发送到"工程师"answers"团队"部分的Javascript。这将显示我从数据库中指定的所有内容,而不必在每次进行更改时手动在JS文件中输入详细信息。

我知道如何使用PHP从数据库检索结果。我需要将从查询中收集的所有结果存储在PHP变量中,并将该PHP变量与各种结果一起发送到脚本。

有人知道如何实现这一点吗?

你不能从php发送任何数据到javascript。相反,您必须通过javascript AJAX请求获取数据。数据在服务器端应该是JSON编码。

查看php JSON编码文档:http://php.net/manual/en/function.json-encode.php

也是Angular $http。得到文档:https://docs.angularjs.org/api/ng/service/http美元

你必须为你的后端环境创建一个REST API接口,将其格式化为JSON,然后使用AngularJS的$resource service来访问数据