使用AngularJs NgResource从localhost加载JSON文件

时间:2013-07-05 18:27:26

标签: javascript angularjs

概述

我正在构建一个应用程序(在MAMP上运行),该应用程序保存联系信息,该信息将扩展以容纳更多数据,例如项目名称和截止日期,一旦该部分正常运作。

问题

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

  1. 我应该如何编写以下内容来访问我的所有数据?
  2. 我最后需要.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();
    2. plunkr文件

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

      project.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"
      }
      ]
      

      app.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>
      

      的index.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>
      

2 个答案:

答案 0 :(得分:10)

由于您不能像使用RESTful样式的URL(这是$resource构建的那样)查询原始JSON文件,您可以获取JSON的副本然后构建您的拥有queryget等,查看数据并返回正确的内容。这有点棘手,因为你也想支持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;
});

您可以像使用任何其他承诺一样使用queryget的结果:

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)的更改;此外,updated Plunker还解决了$routeProvider配置中的问题。

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

答案 1 :(得分: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;
   });

}