Вопрос

I have just started using AngularJS. I would like to send and edit value in the same form. Here is my approach :

  • I fill the input with the scope array with ng-init.
  • And with the scope fields, I store the new value when I click on the button submit.

But it doesn't seem to work... I don't understand why.

index.html

 <form class="form" name="myForm" novalidate>

    <div class="col span12 input"><input type="text" ng-model="fields.name" ng-init="array.name" required /></div>

    <div class="col span12 input"><input type="text" ng-model="fields.age" ng-init="array.age" required /></div>

    <select ng-model="fields.po_id" ng-init="fields.po_id" ng-options="productOwner in productOwners" required></select>

ng Add

 </form>

controllers.js

$scope.productOwners =
[
    {
        "id": 1
    },
    {
        "id": 2
    },
    {
        "id": 3
    },
    {
        "id": 4
    },
];

$scope.array =
[
    {
        "name": "Hello"
    },
    {
        "age": "18"
    },
    {
        "po_id": "2"
    }
]; 

$scope.submit = function(fields){

}
Это было полезно?

Решение

I've created a working Plunker solving your issue.

You had two issues in your code:

1) ng-init="array.age" should be ng-init="fields.age=array.age" and same thing for the other ng-init. You wasn't saving the value in fields so it wasn't updated.

2) Your array definition was faulty.

You should either define array as:

$scope.array = {
        "name": "Hello",
        "age": "18"
    }; 

Or change the call to array in the HTML template like that:

array.name -> array[0].name

array.age -> array[1].age


EDIT:

Updated Plunker

The correct use of ng-options is

for array data sources:
   label for value in array
   select as label for value in array
   label group by group for value in array
   select as label group by group for value in array
for object data sources:
   label for (key , value) in object
   select as label for (key , value) in object
   label group by group for (key, value) in object
   select as label group by group for (key, value) in object

So I've changed your ng-options from ng-options="productOwner in productOwners" to ng-options="productOwner.id for productOwner in productOwners" which is of the type : label for value in array where the label is productOwner.id and the value is the object productOwner.

Moreover, the ng-init is not needed since fields.po_id has no value at the initialization.

But if you want to initialize the value, you can do something like :

ng-init ="fields.po_id = productOwners[0]"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top