user1469734
user1469734

Reputation: 801

Angular setting form with scope?

What I want is a form that I can use for both creating and updating. So I pass before showing

$scope.form = {};

$scope.car = null;
$scope.getCar = function(hash) {
  $http.get('/cars/'+hash).success(function(car) {
      $scope.car = car;
      $scope.form = car;
  });
};

As you can see I add the result of the get to both car and form. Now I'm opening the View:

<h1>{{ form.name }} <small>shows correctly</small></h1>

But a line after that I'm trying almost the same:

<form class="list" ng-submit="createOrUpdateForm(form)">

    <label class="item">
        <span class="input-label">Name</span>
        <input type="text" ng-model="form.name">

Here it's not shown... But when I add the same line after it like this:

<input type="text" ng-model="car.name">

This does work, but then I can't use the ng-submit anymore, because that references to form.

Form some reason I can't set the form scope?

Upvotes: 0

Views: 50

Answers (1)

HankScorpio
HankScorpio

Reputation: 3651

You should not manual assigning anything to form. A "form" is not the same as the data you manage using the form. Neither the empty object {} nor car make sense in that context.

Give the form a name, this will allow angular to assign it to a scope property.

<h1>{{ car.name }} <small>shows correctly</small></h1>

<form name="carForm" ng-submit="createOrUpdateForm(carForm)">

    <label class="item">
        <span class="input-label">Name</span>
        <input type="text" ng-model="car.name">

$scope.createOrUpdateForm = function(form) {
    if(form.$valid) {
        console.log($scope.car.name);
        // POST / PUT your data.
    }
};

Upvotes: 1

Related Questions