使用AngularJs NgResource加载从本地主机JSON文件 [英] use AngularJs NgResource to load JSON file from localhost

查看:138
本文介绍了使用AngularJs NgResource加载从本地主机JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

概述

我建立保存联系人信息,将扩大举行更多的数据,如项目名称和放大器的应用程序(在MAMP运行);最后期限,一旦这部分的功能​​。

问题

当用户访问 /projects.php#/project / 我想他们看到所有的项目名称的列表,链接到他们的详细信息页面。


  1. 应该怎么写我下面来访问我的数据?

我是否需要以.json结尾?

什么是@id办?

收益$资源(数据/ project.json /:身份证',{ID:'@id'});

当用户访问 /projects.php#/project/a-gran-goodn 我想他们看到这个项目的细节(现在,只是名称和放大器;地址)

<醇开始=2>
  • 应该如何我写了下面通过ID返回我的数据?
    $ scope.project = $ routeParams.id? Project.get({ID:$ routeParams.id}):新项目();

  • plunkr文件

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

    project.json

    此文件住在的http://本地主机:8888 / angularjs / ProjectsManager /数据/ project.json

      [
    {地址:3156多灰尘的公路
            蒂内克新泽西州07009-6370美国
    ]
            ID:A-奶奶-goodn
            名:Grania Goodner
            手机:(862)531-9163
    },
    {地址:62红褐色沼泽
            罗德尼村西弗吉尼亚州25911-8091美国
    ]
            ID:B-AIME-defranc
            名:Aimery Defranco
            手机:(681)324-9946
    }
    ]

    app.js

      VAR projectsApp = angular.module('项目',['ngResource']);projectsApp.config(函数($ routeProvider){
      $ routeProvider
              。什么时候('/', {
        控制器:'ProjectListCtrl',
        templateUrl:'谐音/ projectlist.html'})
              。当(项目/:身份证',{
        控制器:'ProjectDetailCtrl',
        templateUrl:'谐音/ projectdetail.html
      })
              。除此以外('/');
    });projectsApp.factory('项目',函数($资源){
      返回$资源(数据/ project.json /:身份证',{ID:'@id'});
    });projectsApp.controller('ProjectListCtrl',函数(项目,$范围){
      $ scope.projects = Project.query();
      的console.log($ scope.projects);
    });projectsApp.controller('ProjectDetailCtrl',函数(项目,$ routeParams,$范围){
      $ scope.project = $ routeParams.id
              ? Project.get({ID:$ routeParams.id})
              : 新项目();
    });

    的谐音/ projectlist.html

     &LT; A HREF =#/项目/级=​​BTN&gt;添加新项目&lt; / A&GT;
    &LT; UL类=无样式&GT;
        &LT;李NG重复=项目工程&GT;
        &LT; D​​IV CLASS =以及&GT;
          &LT; H2&GT;&LT;小&GT; {{project.id}}&LT; /小&GT; {{project.name}}&LT; / H&GT;
          &LT; A HREF =#/项目/ {{project.id}}级=BTN BTN-链接&gt;查看信息为{{project.name}}&LT; / A&GT;
            &LT; / DIV&GT;
      &LT; /李&GT;
    &LT; / UL&GT;

    的谐音/ projectdetails.html

     &LT; H3&GT;信息与LT; / H3 GT&;
    &所述p为H.;名称:{{project.name}}&下; / P&GT;
    &LT; P&GT;电话:{{project.phone}}&LT; / P&GT;
    &LT; p NG重复=,在project.address行&GT; {{}线}&LT; / P&GT;

    的index.php

     &LT; PHP
    标题(访问控制允许来源:*');
    ?&GT;
    &LT;!DOCTYPE HTML&GT;
    &LT; HTML NG-应用=项目&GT;
      &LT; HEAD&GT;
        &LT;间的charset =UTF-8&GT;
        &LT;标题NG绑定=称号NG-斗篷&GT;餐厅和放大器; MDASH;&LT; /标题&GT;    &LT;链接href=\"https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css\"相对=样式&GT;
      &LT; /头&GT;  &LT;机身NG控制器=ProjectListCtrl&GT;
        &LT;一类=品牌的href =#&GT;项目经理&LT; / A&GT;    &LT; D​​IV ID =应用程序容器级=集装箱液&GT;
          &LT; D​​IV CLASS =排液&GT;
            &LT; D​​IV CLASS =span12ID =main的NG-视图&gt;
            &LT; / DIV&GT;&LT;! - 。/ span12 - &GT;
          &LT; / DIV&GT;&LT;! - 。/排液 - &GT;
          &LT;页脚和GT;版权项目和放大器;复印件; 2013&LT; /页脚&GT;
        &LT; / DIV&GT;&LT;! - 。/容器 - &GT;
        &所述; SCRIPT SRC =HTTP://$c$c.jquery.com/jquery-1.10.0.min.js&GT;&下; /脚本&GT;
        &LT;脚本的src =// netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js\"></script>    &LT;! - 不要忘了加载angularjs和角度resource.js - &GT;
        &所述; SCRIPT SRC =htt​​p://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js&GT;&下; /脚本&GT;
        &所述; SCRIPT SRC =htt​​p://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js></script>
        &LT;! - 控制器 - &GT;
        &所述; SCRIPT SRC =app.js&GT;&下; /脚本&GT;
      &LT; /身体GT;
    &LT; / HTML&GT;


    解决方案

    由于像您可以用REST风格样式的网址(这是 $资源建办),而是可以得到JSON的副本,然后建立自己的查询 GET 等,看起来在数据并返回正确的事情。这是一个有点棘手,因为你也想支持新项目,它使用基于文件的存储时,并没有真正意义,但这个例子支持它:

    projectsApp.factory('项目',函数($ HTTP){
      //创建解析为内部project.json数据内部的承诺;
      //我们将使用这一承诺在我们自己的API来获取我们需要的数据。
      VAR JSON = $ http.get('project.json'),然后(功能(响应){
        返回response.data;
      });  //一个基本的JavaScript构造函数来创建新的项目;
      //在数据传递被直接复制到对象。
      //(这是不是最好的设计,而是适用于这个演示。)
      VAR项目=功能(数据){
        如果(数据)angular.copy(数据,这一点);
      };  //查询函数返回解析为一个诺言
      //项目的阵列,每个以JSON。
      Project.query =功能(){
        返回json.then(功能(数据){
          返回Data.Map中(函数(项目){
            返回新的Project(项目);
          });
        })
      };  // get函数返回解析为一个承诺
      //具体的项目,根据ID找到。我们通过循环找到它
      //在所有这些和检查,看是否ID匹配。
      Project.get =功能(ID){
        返回json.then(功能(数据){
          VAR的结果= NULL;
          angular.forEach(数据,功能(项目){
            如果(project.id == id)的结果=新的Project(项目);
          });
          返回结果;
        })
      };  //最后,工厂本身返回整个
      //项目构造器(其中有`query`和`GET`附后)。
      返回项目;
    });

    您可以使用查询的结果 GET 就像任何其他的承诺:

    projectsApp.controller('ProjectListCtrl',函数(项目,$范围){
      $ scope.projects = Project.query();
    });projectsApp.controller('ProjectDetailCtrl',函数(项目,$ routeParams,$范围){
      $ scope.project = $ routeParams.id
              ? Project.get($ routeParams.id)
              : 新项目();
    });

    请注意变更为 Project.get($ routeParams.id);同时,更新了 Plunker 中还修复了问题,你的 $ routeProvider 配置。

    这是一切都在这里展现: http://plnkr.co/edit/mzQhGg?p=$p $ PVIEW

    Overview

    I am building an app (running on MAMP) that holds contact information that will expand to hold more data such as project name & deadline, once this part is functional.

    Questions

    When the user visits /projects.php#/project/ I would like them to see a list of all the project names with a link to their detail page.

    1. How should I write the following to access all of my data?

    Do I need the .json at the end?

    What does the @id do?

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

    When the user visits /projects.php#/project/a-gran-goodn I would like them to see the details about this project(for now, just the name & address).

    1. How should I write the following to return my data by Id? $scope.project = $routeParams.id ? Project.get({id: $routeParams.id}): new Project();

    plunkr file

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

    project.json

    This file lives on 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();
    });
    

    partials/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>
    

    partials/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>
    

    解决方案

    Since you can't query against a raw JSON file like you can with RESTful-style URLs (which is what $resource is built to do), you can instead get a copy of the JSON and then build your own query, get, etc. that looks at the data and returns the right thing. It's a bit tricky because you also want to support new Project, which doesn't really make sense when using a file-backed store, but this example supports it:

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

    You can use the results of query and get like any other promise:

    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();
    });
    

    Note the change to Project.get($routeParams.id); also, the updated Plunker also fixes a problem in your $routeProvider configuration.

    This is all demonstrated here: http://plnkr.co/edit/mzQhGg?p=preview

    这篇关于使用AngularJs NgResource加载从本地主机JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆