AngularJS - ng-repeat,更新尚未定义的模型对象索引

AngularJS - ng-repeat, update a model object index which is not yet defined

本文关键字:模型 对象 索引 未定义 ng-repeat 更新 AngularJS      更新时间:2023-09-26

我有一个数据对象"data"如下,但我需要迭代它们 在另一个称为"值"的数组上,当我更新值时 在视图输入中,我需要相应地更新模型对象"数据",

但问题是索引"B"未在"数据"对象中

定义为 inxdex"a",那么我如何在控制器中更新"数据"对象,对于所有"值"数组索引,包括尚未在"数据"对象中定义的"B"。对于这种情况,是否有其他方法?

控制器

$scope.values=["a","b"];
$scope.data={"a":{name:"A"}};
$scope.updateRate = function(val) {
   $scope.data[val]=//i want the input value here;
};

视图

<tr ng-repeat="v in values">
    <td><input ng-model="data[v].name" type="text" ng-blur="updateRate(v)"></td>
</tr>

为什么不在尝试设置模型之前在控制器中创建所有密钥对:

.controller('myCtrl', ['$scope', function($scope){
    $scope.values = ["a","b"];
    $scope.data = {};  
    for(var i=0;i<$scope.values.length;i++){
        $scope.data[$scope.values[i]] = {};
    }
    $scope.updateRate = function(val){
       $scope.data[val] = //not sure what your wanting to set it to here as the model is already the input value
    }
}]);

http://jsfiddle.net/j82mzfj9/