简体   繁体   中英

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

I have a data object "data" as below, but i need to iterate them over the other array called "values" , and when I update the values in view inputs, i need to update the model object "data" accordingly,

but the problem is index "b" is not defined in "data" object as inxdex "a" so how can i update "data" object in controller, for all the "values" array indexes including "b" which is not yet defined in "data" object. is there any alternative method for this kind of scenario?

controller

$scope.values=["a","b"];
$scope.data={"a":{name:"A"}};

$scope.updateRate = function(val) {
   $scope.data[val]=//i want the input value here;
};

view

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

Why don't you create all your key pairs in the controller before trying to set the model:

.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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM