Utilize ng-model to incorporate an object

I am faced with a challenge when it comes to updating values in a form upon submission. The current setup looks like this:

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

    //what should be added here for ng-model//
    <input type="text" ng-modal ="movie.__"/>
   there may be multiple genre inputs depending on user input

</form>

The data structure submitted by the form will resemble the following format, without considering the ids at this point. I am uncertain about how to deal with creating the genre data, which is an array of objects.

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

Answer №1

To update the list of genres in a movie object in AngularJS, you can create an input field where users can type in a genre and then click a button to add it to the list.

Here is an example implementation:

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>

Answer №2

To begin with, there is a fundamental flaw in your design strategy as you are attempting to allow the user to input any type of data and then match it against a predefined set of information which may be random. I would suggest considering using alternative methods such as multi-select dropdowns or checkboxes. An auto-suggestion feature that confines the user to a predetermined list of genres could also greatly enhance the user experience.

If you still wish to proceed with this approach, there are steps you can take to improve the process.

Separate the ng-model for the entered genre(s) from the form data. This means that in the updateMovie() function, you will need to manipulate the data appropriately.

Allow the user to associate a genre with a simple string:

<input type="text" ng-model ="movie.userGenres"/>

In the updateMovie() method, parse the data based on spaces, commas, etc., and map it to your genres array if feasible. Subsequently, transmit the mapped data instead of the raw inputted string provided by the user.

Answer №3

If you're looking to enhance your tagging system, consider using ngTagInput.

var application = angular.module('application', []);

application.controller('yourController', function() {
    $scope.film = {
      title: '',
      summary: '',
      categories: [],
    };
});


<tags-input id="categories" class="input-border" ng-model="film.categories"
                            placeholder="Categories for film"
                            add-on-comma="true"
                            replace-spaces-with-dashes="false"
                            on-tag-added="$tag.text=$tag.text.toLowerCase()"></tags-input>

To customize the format of genres, convert them into an array like this:

[{text: 'genre1'}, {text: 'genre2'}]

Answer №4

Consider utilizing angular ui-select for a more efficient way to select multiple values. You can find more information about it here: https://github.com/angular-ui/ui-select. Check out some examples on how to use it effectively: http://angular-ui.github.io/ui-select/demo-multiple-selection.html

Another useful feature is the ability to implement your own refresh function that provides a list of available genres along with the entered genre. Learn more about this functionality here: https://github.com/angular-ui/ui-select/wiki/ui-select-choices

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send the chosen value from a dropdown menu to a PHP script

<style type="text/css"> form select { display:none; } form select.active { display:block; } </style> <script type="text/javascript"> window.onload = function () { var allElem = document. ...

Eliminating empty lines from a textarea using jQuery

I have exhaustively attempted every solution I could find both here and on Google, but none of them seem to be working for my issue. Just to clarify, my goal is to eliminate any empty lines from a text area. This is what I have tried so far: <textare ...

What sort of $scope does AngularJS utilize?

I recently started working with Angular, but I am facing an issue with the type of object in Angular. Which $scope is being used in this screen? How can I access the 'title' from it? Below is the code snippet I am working on: define(['an ...

Querying Using Multiple Filter Selectors

Currently, I am in the process of developing a jQuery multiple filter module and have encountered a logic gap in my framework. Within this module, there are numerous div elements each containing data-x and data-y attributes. For instance: <div class= ...

Using Vanilla CSS with React?

This is my first time working on a react app and I'm a bit unsure of the best approach to styling components. Currently, I am creating a separate .css file for each component or page, and including it implicitly. While this method seems the simplest, ...

Tips for encoding and transmitting floating-point data to GLSL from JavaScript/THREE.js and interpreting the output

I need assistance with encoding object positions (x,y,z) and sending them to a GLSL shader for decoding, performing calculations, and then returning the results back to the CPU. I have done some research on this topic and found some relevant resources like ...

Struggling to animate the selector of a nested div in Jquery?

Despite trying numerous variations, I am struggling to identify the correct selector of a nested div. The goal is to animate this particular div, but since no animations are taking place, I suspect that I have not selected the right element. Here is the a ...

Stop jwplayer video from being downloaded on the Chrome mobile browser

Currently, I am facing an issue with the JWPlayer video where I am unable to prevent it from being downloaded. On mobile Chrome browser, if I double click while the video is playing, it gives me the download option, which is not ideal. Despite going throu ...

What is the best way to include quotation marks in the RequestBody when sending a string?

Here is the API-method in question: @PatchMapping("/{id}") public ResponseEntity<?> partialProjectUpdate(@PathVariable long id, @RequestBody EntryStatus status) throws DailyEntryNotFoundException { return dailyEntryService.partialDailyEntryUpd ...

No elements can be located within the iframe as per Cypress's search

I've been attempting to access elements within an iframe using the guidance provided in this article here, but I'm facing an issue where Cypress is unable to locate anything within the iframe. Below is a snippet of my test code: describe('s ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

What is the process for modifying the value of a "Value" service?

I have a value that is injected and used throughout my application. I now find myself needing to update this value, but it isn't reflecting the change. Below is an example of the scenario: angular.module('app', ['ngRoute']) // Def ...

Resolve the route expression before the API request is fully processed

As a hobby coder, I have some gaps in my knowledge and despite trying various solutions, I have not been able to solve this issue. Idea Outcome My goal is to call my Express server, retrieve data from an external API, and render the data once it's f ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

Is it possible to view the frames/packets being transmitted from an EJS or HTML form to the Express backend using Express Js?

My current computer science assignment involves visually representing the data transfer process between a frontend and backend. I don't need to show the full data, just the flow of chunks and how it navigates through protocols. Could someone please g ...

Comparison of performance between Synchronous and Immediate Asynchronous execution in benchmarking

Curious about the performance differences between synchronous and asynchronous data conversions, particularly in a scenario where an async function would return results immediately, I decided to conduct a simple benchmark test. const { performance } = req ...

Verify if a parent element contains a specific class, and if it does, then add a custom style to that

I am currently working on a challenge where I need to hover over an element, check if its class contains a specific prefix, and then apply some styles to that particular element. The issue I'm facing is that when the element has a parent div with a pr ...

Invoke Selenium using JavaScript

Imagine I have this (fictional) JavaScript snippet: asynchronousOperation.addEventListener("completed", function (event) { if (event.property == "required value") tell Selenium we are good; else tell Selenium the test failed; }); ...