【问题标题】:Angular - Select array in json objectAngular - 在 json 对象中选择数组
【发布时间】:2013-10-08 17:11:18
【问题描述】:

我有一个 json 数组对象,如下所示:

[
    {
        "id": 1,
        "name": "John Smith",
        "age": 52
    },
    {
        "id": 2,
        "name": "Jane Walters",
        "age": 43
    },
    {
        "id": 3,
        "name": "Mike Wilson",
        "age": 65
    },
    {
        "id": 4,
        "name": "Tom Samuels",
        "age": 29
    }
]

我在“索引”页面上显示所有这些名称,并且我只想在每个“字符/[id]”页面上显示一个。这是我的索引页控制器:

angular.module('myApp.controllers', []).
    controller('index', ['$scope', 'characters', function($scope, c){
        $scope.characters = c.getCharacters;
    }]);

这里是“字符”服务:

factory('characters', function($resource){
    return $resource('JSON/characters.json', {}, 
    {
        'getCharacters':    {method: 'GET', isArray:true}
    }); 
});

视图是标准样板。

我的问题是,如何为“character/[id]”路由创建服务(或操作控制器中的对象),以便它只根据 JSON id 选择单个数组?

我在 angularjs.org 上做了 phonecat 演示,但该演示为每部手机使用单独的 JSON 文件,然后为索引页面使用一个大的 JSON 文件。我想避免这种情况。

最后一件事:我正在使用 angular-seed,所以我想保持那里使用的语法。我尝试了很多不同的方法,但都没有成功。

【问题讨论】:

    标签: json angularjs


    【解决方案1】:

    我自己的项目中的示例:

    控制器:

    app.controller("prodDetalleController", ["$scope","$http","$routeParams", function($scope,$http,$routeParams ){    
    
      vm = this;
      $scope.id = $routeParams.idProducto;
    
    
        // Listado de productos
        $http.get("_producto.php?id="+$scope.id)
        .success(function (respuesta) 
        {
            vm.producto = respuesta;}
        )
        .error(function(){
            vm.producto = "Error: no hay datos.";
        }); 
    
    }]); // fin ctrl
    

    在 PHP 中:

    <?php
    
     $id = $_GET['id'];
     //echo $id;
    
    $conn = @new mysqli('localhost', 'root','buenosaires','martin_db');
    
    $result = $conn->query("SELECT * FROM productos WHERE idProducto=$id");
    
    $myArray = array();
    

    ...

    并且在视图中:

    {{producto.titulo}}
    {{producto.descripcion}}
    

    ...

    【讨论】:

      【解决方案2】:

      基本上,您是在问如何从路由 url 中获取 id。

      定义你的角色路径路径,如:

      /character/:id
      

      在你的角色控制器中像

      ....controller('characterCtrl', ['$scope', 'characters','$routeParams' function($scope, c,$params){
          $scope.characters = c.getCharacters;
          //you have $params.id here as the id from the url
      }]);
      

      在注释行上循环通过$scope.characters 以找到具有匹配id 的行并将其设置为另一个范围变量。 在提供帮助时,包含当前页面/视图和控制器的 jsFiddle 可能会更有用。

      【讨论】:

      • 我会遍历控制器中的数组,但在加载到浏览器之前它是空的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2019-05-28
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多