这是我要做的:
在您的 index.php/html/whatever 中包含一个带有 Angular 服务的脚本标记,该服务捕获并返回您的数据。
<html>
<head>
<!-- Include Angular -->
<script type="text/javascript">
// By creating this service, we can capture the data from
// from the server and store it.
angular.module('myApp').factory('usrData', [function () {
var data = {};
data.usrData = <?php echo $usrService->getUserData(); ?>;
return data;
}]);
</script>
</head>
<body>
<!-- Continue with HTML -->
然后,您可以拥有另一个服务,例如在 service.js 中,用于收集您从服务器捕获的内联数据以及您通过 AJAX 查询的其他数据,并创建一个 API 来管理这一切.为此,您可以将 HTML 中的内联服务作为依赖项注入到此 dataServices 模块中:
angular.module('myApp').factory('dataServices', [
'$http', 'otherData', 'usrData', // <-- These are the module dependencies
function ($http, otherData, usrData) { // <-- Here you use them as parameters
'use strict';
var dataModel = {
otherData: otherData,
usrData: usrData
};
return { // Data service API
query: function (dataType) {
// returns data
// API continues …
最后,在你的控制器中,比如 controller.js,你注入这个 dataServices 服务作为一个依赖来通过这个 API 检索和保存你的数据:
angular.module('myApp').controller('UsrWidget', [
'$scope', 'dataServices',
function ctrlrPtHeader($scope, dataServices) {
"use strict";
$scope.usrData = dataServices.query('usrData');
// And now you have the data.
现在,控制器可以直接访问内联到 HTML 中的 usrData 服务,但我更喜欢全局 API 来管理我的数据,方法是提供一个漂亮的 API 脚本并将我的 HTML 保持为尽可能干净。整个事情的秘诀是将所有数据封装在 Angular 环境中,并通过依赖注入和工厂方法传递信息。