2

Here is the Plunker that describe my problem with dynamic binding in Angularjs.

http://plnkr.co/edit/fGgtOZ5IrJVo9QasQALc?p=preview

Before using Angularjs, I am used to using the input name/value like the following to generate desirable data structure for back end processing

<input type="text" name="computer[details][][purchaseddate]" />

<input type="text" name="computer[details][][warrantyperiod]" />

With Angularjs ng-model, it is possible to bind a complex data structure like

<input type="text" ng-model="computer.parts[0].name" />

However it does not work with dynamic property like the following:

<input type="text" ng-model="computer.details[0].name" />

Angular keeps telling me that I am trying to set property 'name' to undefined 'details[0]', I am aware of that but are there any ways to get the same behavior with previous input's name/value where I can specify dynamic property without having to declare it first?

Thank you,

1
  • Can you describe your use case why you would want to do this? Commented Jun 25, 2013 at 16:46

2 Answers 2

3

Binding to attributes that don't exist yet works. You can bind to a.b.c even if $scope.a does not exists. Angular creates the objects and attributes on-the-fly.

<input type="text" ng-model="a.b.c" />

But you are trying to bind to an array element that does not exist yet:

<input type="text" ng-model="a.b[0].c" />

Angular would have instantiate the array and then push an empty object in it and then assign it's name. Apparently this does not work.

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

Comments

1

I ran into the same situation and tried everything.

This is how I was able to get dynamic values inside 2 deep ng-repeat:

JS:

$scope.newContact = {
    name: [],
    phone: [],
    email: [],
    notes: []
};

$scope.saveNewContact = function (idx) {
    console.log($scope.newContact.name[idx]);
};

HTML:

<input type="text" ng-model="newContact.name[$index]" />
<input type="text" ng-model="newContact.phone[$index]" />
<input type="text" ng-model="newContact.email[$index]" />
<input type="text" ng-model="newContact.notes[$index]" />
<button ng-click="saveNewContact($index)">Save</button>

Comments

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.