从json对象获取特定参数值

时间:2016-02-22 07:34:39

标签: javascript angularjs

我已定义工厂,如下所示

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

4 个答案:

答案 0 :(得分:1)

试试这个:

app.controller('ChartCtrl4', function ($scope, Category) {
   Category.get()
    .$promise.then(function(response) {
      $scope.totalCategory = response.data.total;
  });
});

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果我理解正确,那应该是: SELECT F1, MAX(F2) AS F2, F3 FROM MyTable WHERE (F3 & 8) != 0 GROUP BY F1; 也许你不熟悉$scope.category.data.total。 这是一篇好文章:http://www.webmonkey.com/2010/02/get_started_with_json/

答案 3 :(得分:0)

$ scope.category.data.total将获取属性,但检查以确保该属性实际存在并在访问之前具有值是明智的。

$scope.totalCategory = 0;

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

为了安全起见。