从 json 对象获取特定参数值

Get particular parameter value from json object

本文关键字:参数 获取 json 对象      更新时间:2023-09-26

我已经定义了工厂,如下所示

app.factory('Category', function($resource,$rootScope) {
  return $resource('api/category');
});

这是我的控制器:

app.controller('ChartCtrl4', function ($scope, Category) {
   $scope.category = Category.get();
   $scope.totalCategory = ???      //total:2
});

从 Category.get 获得的数据:

{
 message: "Category Retrieved Successfully",
 data: {
  total: 2,
  per_page: 10,
  current_page: 1,
  last_page: 1,
  next_page_url: null,
  prev_page_url: null,
  from: 1,
  to: 1,
  data: [
   {
    ...
   },{
    ....
   }
 ]
}
}

我想在我的控制器中访问总计的值,即 2

试试这个:

app.controller('ChartCtrl4', function ($scope, Category) {
   Category.get()
    .$promise.then(function(response) {
      $scope.totalCategory = response.data.total;
  });
});
var d = {
 message: "Category Retrieved Successfully",
 data: {
  total: 2,
  per_page: 10,
  current_page: 1,
  last_page: 1,
  next_page_url: null,
  prev_page_url: null,
  from: 1,
  to: 1,
  data: [
   {
    ...
   },{
    ....
   }
 ]
}
}

d.data.total => 2

如果我理解正确,应该是: $scope.category.data.total也许你不熟悉json.这是一篇好文章:http://www.webmonkey.com/2010/02/get_started_with_json/

$scope.category.data.total 会得到属性,但明智的做法是检查以确保该属性确实存在并且具有值,然后再访问它。

$scope.totalCategory = 0;
if ($scope.category && $scope.category.data && $scope.category.data.total) {
  $scope.totalCategory = $scope.category.data.total;
}

只是为了安全

起见。