Creating dynamic ng-model with angular

Asked

Viewed 2,277 times

1

I need to create a model name dynamically, but when creating obj the angular does not accept that I try to create the obj name dynamically. Has anyone ever done this or knows how to proceed?

The problem is occurring in the data-ng-model, wanted to create an object with the name form with all its attributes dynamically.

Below is the HTML example

<div data-ng-repeat="campos in lista">
      <div data-ng-switch="campo.type">
          <div data-ng-switch-when="text">
               <label data-ng-if="campo.label">{{campo.label}}</label>
               <input type="text" name="{{campo.name}}" placeholder="{{campo.placeholder}}" data-ng-model="form.{{campo.name}}" />
          </div>
      </div>
</div>

1 answer

4


Instead of using form.{{campo.name}}, utilize form[campo.name].

Besides, I don’t see any problems.

  • In case it will create a vector and not a correct object?

  • 2

    You are correct and wrong. Simply put, an object, in Javascript, is a vector (a map, if it is methodical) of attributes. That is, structurally, a vector and an object are very similar. So much so that there is no typeof arr === "array" and the method should be used Array.isArray. This article can help you understand a little more (in English) http://www.quirksmode.org/js/associative.html

  • Anyway, I hadn’t thought of it that way. Thank you.

  • 1

    Solve my problem this way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.