0

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>
2
  • 1
    Is the input value not updated properly into data[v].name, since that's what you've bound to ngModel? Otherwise, have you tried using $event? As in updateRate($event, v) Commented Jan 14, 2015 at 14:04
  • data[v] for index "b" is new to that model object, how can i set it? it's not going to automatically created right? when i type on the input box Commented Jan 14, 2015 at 14:06

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

6 Comments

can't i push the new value to data object? so it'll be synced with view?
No the ng-model will create a new scope value for you but not dynamically for example you can do ng-model="object.object.primitive" and it will create it but you cannot do ng-model="object[dynamicKey].primitive"
I mean in the controller, because the data object is multidimensional huge array
Yes doing what I have done in my fiddle is setting up the model object for you, by default a controller and view work in sync when using ng-model so if you now edit an input value it will set data['a'].name
Yes you can check if it exists in the loop.... if(!$scope.data[$scope.values[i]]) $scope.data[$scope.values[i]] = {} I don't really understand your problem, but if your going to se a dynamic model iit has to exist on the scope....
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.