如何使用数组/对象循环遍历数组并在Angular中分配属性新值?

时间:2017-05-16 23:11:08

标签: javascript angularjs object for-loop

我有一个数组和对象数组。我有一个函数,我想为一个属性分配一个值(例如' call':'' $ scope.companies [0]。用户变成用户检查的任何值在复选框中)。我研究了它,我不知道该怎么做,到目前为止我所做的一切都是错的。非常感谢!!

      <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 个答案:

答案 0 :(得分: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; }   

如果您正在寻找通过公司循环,那么嵌套2循环,一个循环公司和另一个循环用户与上述代码中给出的相同的想法。