通过数组访问AngularJS模型对象?

时间:2014-04-19 15:17:49

标签: javascript angularjs

我有一个有趣的问题(至少对我来说)。

我正在进行一个项目,我们从API中获取数据,并在数组中嵌套一组对象。我们希望能够单独显示/编辑它们。棘手的部分是从视图中获取它们。这是使用类似但已编制的场景的设置。

用户导航到/ profile / exploit / 1

理想情况下,我们抓取该参数并使用它来过滤数组。这是JS的示例(没有param,我为了简单而硬编码值)

var app = angular.module('app',[]);

app.controller('AppCtrl', ['$scope',
  function($scope) {
    // The data is coming in from the API in a similar format.
    // There is an array with objects in it, and we need 
    // display and/or edit those individual records
    // This is a way simplified version of it
    // (and nothing like the real data, haha)
    $scope.profile = {
      name: "Alexander",
      location: "Earth",
      exploits: [
        {name: "Conquer Achaemenid empire", year: "334 BC", duration: 3},
        {name: "Conquer the Balkans", year: "335 BC", duration: 4},
        {name: "Conquer the Persian Empire", year: "334 BC", duration: 6}
      ],
    }
    // I planned to set this with a parameter /profile/exploits/1
    e = 1;
  }]);

而且,这是HTML

<html lang="en" ng-app="app">

  <head>
    <script data-require="angular.js@1.2.16" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js"></script>
  </head>

  <body>
    <div ng-controller="AppCtrl">
      Name: {{ profile.exploits[0].name }}<br/>
      Year: {{ profile.exploits[0].year }}<br/>
      Duration: {{ profile.exploits[0].duration }} months
    </div>
  </body>

</html>

我想做的是:     {{profile.exploits [e] .name}}

其中e设置数组中的记录。但我不能为我的生活弄清楚如何实现这一目标。认真地希望这是一件非常简单的事情。

我在这里嘲笑http://embed.plnkr.co/XhIlJt8BGCAkw70tRTgn/preview

1 个答案:

答案 0 :(得分:0)

您可以使用$ location从网址中提取信息。所以尝试这样的事情:

var app = angular.module('app',[]);

app.controller('AppCtrl', ['$scope', '$location', function($scope, $location) {

  $scope.profile = {
    name: "Alexander",
    location: "Earth",
    exploits: [
      {name: "Conquer Achaemenid empire", year: "334 BC", duration: 3},
      {name: "Conquer the Balkans", year: "335 BC", duration: 4},
      {name: "Conquer the Persian Empire", year: "334 BC", duration: 6}
    ],
  }

  $scope.activeProfile = function() {
    var i = $location.path();  //Should be your desired value
    return $scope.profile.exploits[i];
  }

}]);

希望这有帮助,

约旦