4

概述

我正在构建一个应用程序(在 MAMP 上运行),其中包含联系信息,一旦这部分功能正常,该信息将扩展以包含更多数据,例如项目名称和截止日期。

问题

当用户访问时,/projects.php#/project/我希望他们看到所有项目名称的列表以及指向其详细信息页面的链接。

  1. 我应该如何编写以下内容来访问我的所有数据?

最后我需要 .json 吗?

@id 有什么作用?

return $resource('data/project.json/:id', {id: '@id'});

当用户访问时,/projects.php#/project/a-gran-goodn我希望他们查看有关此项目的详细信息(现在,只是名称和地址)。

  1. 我应该如何编写以下内容以按 Id 返回我的数据? $scope.project = $routeParams.id ? Project.get({id: $routeParams.id}): new Project();

plunkr 文件

http://plnkr.co/edit/7YPBog

项目.json

该文件继续存在http://localhost:8888/angularjs/ProjectsManager/data/project.json

[
{ "address" : [ " 3156 Dusty Highway",
        " Teaneck New Jersey 07009-6370 US"
],
        "id" : "a-gran-goodn",
        "name" : "Grania Goodner",
        "phone" : " (862) 531-9163"
},
{ "address" : [ " 62 Red Fawn Moor",
        " Rodney Village West Virginia 25911-8091 US"
],
        "id" : "b-aime-defranc",
        "name" : "Aimery Defranco",
        "phone" : " (681) 324-9946"
}
]

应用程序.js

var projectsApp = angular.module('projects', ['ngResource']);

projectsApp.config(function($routeProvider) {
  $routeProvider
          .when('/', {
    controller: 'ProjectListCtrl',
    templateUrl: 'partials/projectlist.html'})
          .when('project/:id', {
    controller: 'ProjectDetailCtrl',
    templateUrl: 'partials/projectdetail.html'
  })
          .otherwise('/');
});

projectsApp.factory('Project', function($resource) {
  return $resource('data/project.json/:id', {id: '@id'});
});

projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
  $scope.projects = Project.query();
  console.log($scope.projects);
});

projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
  $scope.project = $routeParams.id
          ? Project.get({id: $routeParams.id})
          : new Project();
});

部分/projectlist.html

<a href="#/project/" class="btn">Add new item</a>
<ul class="unstyled">
    <li ng-repeat="project in projects">
    <div class="well">    
      <h2><small>{{project.id}}</small> {{project.name}}</h2>
      <a href="#/project/{{project.id}}" class="btn btn-link">View Info for {{project.name}}</a>
        </div>
  </li>
</ul>

部分/projectdetails.html

<h3>Information</h3>
<p>Name: {{project.name}}</p>
<p>Phone Number: {{project.phone}}</p>
<p ng-repeat="line in project.address">{{line}}</p>

索引.php

<?php
header('Access-Control-Allow-Origin: *');
?>
<!doctype html>
<html ng-app="projects">
  <head>
    <meta charset="utf-8">
    <title ng-bind="title" ng-cloak>Restaurant &mdash;</title>

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
  </head>

  <body ng-controller="ProjectListCtrl">
    <a class="brand" href="#">Projects Manager</a>

    <div id="app-container" class="container-fluid">
      <div class="row-fluid">
        <div class="span12" id="main" ng-view>
        </div><!--/.span12-->
      </div><!--/.row-fluid-->
      <footer>Copyright Projects &copy; 2013</footer>
    </div><!--/.container-->


    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

    <!-- Don't forget to load angularjs AND angular-resource.js --> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js></script>
    <!--Controllers-->
    <script src="app.js"></script>
  </body>
</html>
4

2 回答 2

10

由于您无法像使用 RESTful 样式的 URL(这$resource是构建的目的)那样查询原始 JSON 文件,因此您可以获取 JSON 的副本,然后构建您自己的query,get等数据并返回正确的东西。这有点棘手,因为您还想支持new Project,这在使用文件支持的存储时实际上没有意义,但是这个示例支持它:

projectsApp.factory('Project', function($http) {
  // Create an internal promise that resolves to the data inside project.json;
  // we'll use this promise in our own API to get the data we need.
  var json = $http.get('project.json').then(function(response) {
    return response.data;
  });

  // A basic JavaScript constructor to create new projects;
  // passed in data gets copied directly to the object.
  // (This is not the best design, but works for this demo.)
  var Project = function(data) {
    if (data) angular.copy(data, this);
  };

  // The query function returns an promise that resolves to
  // an array of Projects, one for each in the JSON.
  Project.query = function() {
    return json.then(function(data) {
      return data.map(function(project) {
        return new Project(project);
      });
    })
  };

  // The get function returns a promise that resolves to a
  // specific project, found by ID. We find it by looping
  // over all of them and checking to see if the IDs match.
  Project.get = function(id) {
    return json.then(function(data) {
      var result = null;
      angular.forEach(data, function(project) {
        if (project.id == id) result = new Project(project);
      });
      return result;
    })
  };

  // Finally, the factory itself returns the entire
  // Project constructor (which has `query` and `get` attached).
  return Project;
});

你可以像使用任何其他 Promise 一样使用queryand的结果:get

projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
  $scope.projects = Project.query();
});

projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
  $scope.project = $routeParams.id
          ? Project.get($routeParams.id)
          : new Project();
});

注意更改为Project.get($routeParams.id); 此外,更新后的 Plunker还修复了您的$routeProvider配置中的问题。

这一切都在这里展示:http ://plnkr.co/edit/mzQhGg?p=preview

于 2013-07-05T20:56:39.887 回答
2

我将在此处粘贴一个通用代码,用于从您的本地或远程服务器获取 json,也许它会对您有所帮助:

它使用一个工厂,您可以在需要时调用它。

app.factory('jsonFactory', function($http) {  
  var jsonFactory= {      
    fromServer: function() {        
        var url = 'http://example.com/json.json';
            var promise = $http.jsonp(url).then(function (response) {
          return response.data;
        });      
      return promise;
    },
    hospitals: function() {     
        var url = 'jsons/hospitals.js';               
            var promise = $http.get(url).then(function (response) {
          return response.data;
        });      
      return promise;
    }        
    };
  return jsonFactory;
});

然后当你需要调用它时:

function cardinalCtrl(jsonFactory, $scope, $filter, $routeParams) {
   jsonFactory.hospitals().then(function(d){
        $scope.hospitals=d.hospitals;
   });
   jsonFactory.fromServer().then(function(d){
        $scope.fromServer=d.hospitals;
   });

}
于 2013-07-05T18:43:40.647 回答