2016-09-23 53 views
0

我是AngularJS的新手。我從SQL獲取數據到AngularJS。我能夠以ng-repeat的形式顯示數據,但我想從我的控制器中的數據庫中傳遞的數組的某個屬性的值用於其他函數中。如何在AngularJS中獲取數組屬性的值

下面是我得到數據的控制器。 $ scope.candidates將候選對象的全部數據存儲在一個數組中。我只想得到名字。有沒有什麼像$ scope.candidates.Firstname?

app.controller('CandidateCtrl', ['$scope', 'CandidateService', 
    // we inject CandidatetService inject becuse we call getAll method for get all student 
function ($scope, CandidateService) { 
    // this is base url 
    var baseUrl = '/api/Candidate/'; 
    // get all candidate from databse 
    $scope.getCandidates = function() { 
     var apiRoute = baseUrl + 'GetCandidates/'; 
     var _candidate = CandidateService.getAll(apiRoute); 
     _candidate.then(function (response) { 
      $scope.candidates = response.data; 
     }, 
     function (error) { 
      console.log("Error: " + error); 
     }); 
    } 
    $scope.getCandidates(); 

}]); 
+1

您已經提取了整個數據,只顯示名字。如果您想節省網絡流量,請僅從服務器發回。 –

回答

0

在模板中,你會與你收集NG重複的元素(在這個例子中一個div)。然後用NG-重複的DIV中,你將有另一個元素(在這個例子中另一個DIV),您會訪問您的集合中的單個項目的性質:

< div ng-repeat="candi in candidates"> 
    <div>{{candi.Firstname}}</div> 
< /div> 

如果你想第一個名稱的集合在JavaScript中,您可以使用地圖功能:

var firstNames = $scope.candidates.map(function(c) { return c.Firstname; });