2017-05-16 54 views
0

我有一個數組和對象的數組。我有一個函數,我希望給一個屬性賦值(例如$ scope.companies [0]中的'call':''.users變成用戶在複選框中檢查的任何值)。我研究過它,但我不知道該怎麼做,到目前爲止我所做的一切都是錯誤的。非常感謝!!如何在數組中循環數組/對象並在Angular中賦值屬性的新值?

 <form action="" ng-click="change(key)"> 
     <input ng-model="key.call"type="checkbox"">Call 
     <br> 
     <input ng-model="key.person"type="checkbox" >Person 
     <br> 
     <input type="checkbox"ng-model="key.dial">Dial 
     <br> 
     <input type="checkbox" ng-model="key.voice">Voice   
    </form> 

app.controller('appCtrl', function($scope) { 
    $scope.companies = [{ 
     name: 'The Best Company Denim', 
     users: [{ 
      firstName: 'Alex', 
      lastName: 'D', 
      number: 1234, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }, { 
      firstName: 'Sarah', 
      lastName: 't', 
      number: 14, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }, { 
      firstName: 'J', 
      lastName: 'd', 
      number: 07, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }] 
    }, { 
     name: 'The Best Company Elegant', 
     users: [{ 
      firstName: 'Alx', 
      lastName: 'B', 
      number: 1234, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }, { 
      firstName: 'Seth', 
      lastName: 'w', 
      number: 12, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }, { 
      firstName: 'J.S', 
      lastName: 'B', 
      number: 7. 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }] 
    }, { 
     name: 'The Best Company by Julia', 
     users: [{ 
      firstName: 'Aleddddx', 
      lastName: 'l', 
      number: 1234, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }, { 
      firstName: 'Maggy', 
      lastName: 'n', 
      number: 1, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }, { 
      firstName: 'Ja', 
      lastName: 'Key', 
      number: 123, 
      call: '', 
      person: '', 
      dial: '', 
      voice: '' 
     }] 
    }] 

    $scope.change = function(key) { 
     for (var i = 0; i < $scope.companies[0].users; i++) { 
      $scope.companies[0].users[i].call: key) 
    } 
} 
}); 

回答

1

根據上述代碼,$scope.companies[0].users是一個數組,其中有一個length屬性,讓你在它的項數。那麼你的代碼將是:

$scope.change = function(key) { for (var i = 0; i < $scope.companies[0].users.length; i++) { $scope.companies[0].users[i].call = key; }

如果您正在尋找通過公司循環太多,那麼for循環,一個循環公司巢2,另一種循環用戶提供上面的代碼給出了相同的想法。

+0

非常感謝您的回答。我唯一不明白的是,當我console.log $ scope.companies [0] .users [i],例如在複選框中選擇'call'時,它會給我一個對象(所以call = object)改變呼叫=「」來呼叫=真。 – javascripting