Invictus Invictus - 4 months ago 29
Javascript Question

Add object using ng-model

I have a form which updates values on submit like this

<form ng-submit="updateMovie()">
<input type="text" ng-model="movie.title"/>
<input type="text" ng-model="movie.rating"/>

//what to attach here at ng-model//
<input type="text" ng-modal ="movie.__"/>
there could be many genre inputs based on how many user wants to input

</form>


The object submitted by the form will be of the following type. For the moment lets ignore the ids. I dont know how can I create the genre
i.e. Array of objects

"id": 4792,
"title": "Insidious",
"rating": "7.0",
"genres": [
{
"id": 3,
"name": "horror"
},
{
"id": 7,
"name": "Drama"
}
]

Answer

You can add into a list (movie.genres) everything that the user types and click in a button.

So you can have something like this:

angular.module("app", [])

.controller('mainCtrl', function($scope) {
  $scope.movie = {};

  $scope.movie.genres = [];
  $scope.add = function() {
    if ($scope.genre) {
      $scope.movie.genres.push($scope.genre);
      $scope.genre = '';
    }
  }
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <form ng-submit="updateMovie()">
    <label for="title">Title: </label>
    <input type="text" id="title" ng-model="movie.title">
    <br>
    <label for="rating">Rating: </label>
    <input type="text" id="rating" ng-model="movie.rating">
    <br>
    <label for="genre">Genre: </label>
    <input type="text" id="genre" ng-model="genre">
    <button type="button" ng-click="add()">Add genre</button>
  </form>
</body>

</html>

Comments