Is there a way to transfer textbox value to ng-repeat in AngularJS?

1) The Industry dropdown menu corresponds with a code textbox. Depending on the selected industry, the code will change accordingly.

2) There is a dynamic feature to add or delete Movie Names and Directors' names.

In this table, there are three columns: Movie Name, Director, and Industry Code.

We can dynamically add Movie Names and Directors' names, but the Industry Code needs to be selected from the aforementioned dropdown menu.

Whenever the Industry field is changed, a new code will be generated (e.g., selecting 'Tamil' will produce code 'TN'). Based on the chosen industry, all rows containing Industry Codes in the table should be updated.

Demo

<div data-ng-app data-ng-controller="myCtrl">
  <label>Industry</label>
  <select ng-model="data" ng-options="data as data.name for data in datas">
  </select>
   <label>code</label>
   <input type="text" ng-model="data.code" disabled/>


<ul>
            <li>Movie Name</li>
            <li><input type="text" ng-model="name" /></li>
        </ul>
        <ul>
            <li>Name of Director</li>
            <li><input type="text" ng-model="director" /></li>
        </ul>
        <ul>
            <li></li><li><button ng-click="addRow()"> Add Row </button></li>
        </ul>
         <table> 
            <tr>
                <th>NO</th>
                    <th>Movie Name</th>
                        <th>Director</th>
                        <th>Industry Code</th>
            </tr>

            <tr ng-repeat="movies in movieArray">
                <td><label>{{$index + 1}}</label></td>
                <td><label>{{movies.name}}</label></td>
                <td><label>{{movies.director}}</label></td>
                <td><label>{{movies.code}}</label></td>
                <td><input type="checkbox" ng-model="movies.Remove"/></td>
            </tr>
        </table>

        <div>
            <button ng-click="submit()">Submit Data</button>   
                <button ng-click="removeRow()">Remove Row</button>
        </div>

        <div id="display" style="padding:10px 0;">{{display}}</div>

controller:

function myCtrl($scope){
 $scope.datas = [{
    "id": 3,
    "name": "Tamil",
    "code": "TN"
  }, {
    "id": 4,
    "name": "English",
    "code": "EN"
  },
  {
    "id": 5,
    "name": "Telugu",
    "code": "TE"
  }]


     $scope.movieArray =
        [
            { 'name': 'Total Eclipse', 'director': 'Agniezka Hollan' ,'code': 'TN'},
            { 'name': 'My Left Foot', 'director': 'Jim Sheridan','code': 'TN' },
            { 'name': 'Forest Gump', 'director': 'Robert Zemeckis','code': 'TN' }
        ];

        // GET VALUES FROM INPUT BOXES AND ADD A NEW ROW TO THE TABLE.
        $scope.addRow = function () {
            if ($scope.name != undefined && $scope.director != undefined) {
                var movie = [];
                movie.name = $scope.name;
                movie.director = $scope.director;

                $scope.movieArray.push(movie);

                // CLEAR TEXTBOX.
                $scope.name = null;
                $scope.director = null;
            }
        };

        // REMOVE SELECTED ROW(s) FROM TABLE.
        $scope.removeRow = function () {
            var arrMovie = [];
            angular.forEach($scope.movieArray, function (value) {
                if (!value.Remove) {
                    arrMovie.push(value);
                }
            });
            $scope.movieArray = arrMovie;
        };

        // FINALLY SUBMIT THE DATA.
        $scope.submit = function () {
            var arrMovie = [];
            angular.forEach($scope.movieArray, function (value) {
                arrMovie.push('Name:' + value.name + ', Director:' + value.director);
            });
            $scope.display = arrMovie;
        };
}

Answer №1

To solve this issue, consider implementing an ng-change function. Here is a sample code snippet that demonstrates how to do this: http://jsfiddle.net/nymdjf5f/5/

 $scope.changeindustry=function()
        {
        for(var a in $scope.movieArray)
        {
        $scope.movieArray[a].code=$scope.data.code;
        }

        };

Answer №2

function handleData($scope) {
  $scope.dataList = [{
      "id": 3,
      "name": "Tamil",
      "code": "TN"
    }, {
      "id": 4,
      "name": "English",
      "code": "EN"
    },
    {
      "id": 5,
      "name": "Telugu",
      "code": "TE"
    }
  ]

  $scope.modifyDropdown = function(data) {

  }
  $scope.movieLibrary = [{
      'name': 'Total Eclipse',
      'director': 'Agniezka Hollan',
      'code': 'TN'
    },
    {
      'name': 'My Left Foot',
      'director': 'Jim Sheridan',
      'code': 'TN'
    },
    {
      'name': 'Forest Gump',
      'director': 'Robert Zemeckis',
      'code': 'TN'
    }
  ];
  $scope.chosenItem = {
    'val': ''
  }
  $scope.modifyDropdown = function(){
       $scope.movieLibrary.forEach(function(val, i) {
         val['code']      = $scope.chosenItem['val']['code']
      }) 
   }
  // Add a new row to the table based on input values.
  $scope.addRow = function() {
    if ($scope.name != undefined && $scope.director != undefined && $scope.chosenItem['val']['code']) {
      var found = 0
      $scope.movieLibrary.forEach(function(val, i) {
        if (val['name'] == $scope.name && val['director'] == $scope.director) {
          val['code'] = $scope.chosenItem['val']['code'];
          found = 1;
        }
         val['code']      = $scope.chosenItem['val']['code']
      })
      if (found) {
        $scope.name = null;
        $scope.director = null;
        $scope.chosenItem = {
          'val': ''
        };
        return
      }
      var movie = {};
      movie.name = $scope.name;
      movie.director = $scope.director;
      movie.code = $scope.chosenItem['val']['code'];
      movie.industry = $scope.chosenItem['val']['name'];
      $scope.movieLibrary.push(movie);

      // Clear input fields.
      $scope.name = null;
      $scope.director = null;
      $scope.chosenItem = {
        'val': ''
      }
    }
  };

  // Remove selected row(s) from the table.
  $scope.removeRow = function() {
    var updatedMovies = [];
    angular.forEach($scope.movieLibrary, function(value) {
      if (!value.Remove) {
        updatedMovies.push(value);
      }
    });
    $scope.movieLibrary = updatedMovies;
  };

  // Submit the data for display.
  $scope.submitData = function() {
    var infoArray = [];
    angular.forEach($scope.movieLibrary, function(value) {
      infoArray.push('Name:' + value.name + ', Director:' + value.director+'code:'+value.code);
    });
    $scope.displayInfo = infoArray;
  };
}
div {
  font: 15px Verdana;
  width: 450px;
}

ul {
  padding: 0;
  margin: 2px 5px;
  list-style: none;
  border: 0;
  float: left;
  width: 100%;
}

li {
  width: 50%;
  float: left;
  display: inline-block;
}

table,
input {
  text-align: left;
  font: 13px Verdana;
}

table,
td,
th {
  margin: 10px 0;
  padding: 2px 10px;
}

td,
th {
  border: solid 1px #CCC;
}

button {
  font: 13px Verdana;
  padding: 3px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app data-ng-controller="handleData">
  <label>Industry</label>
  <select ng-model="chosenItem['val']" ng-options="data as data.name for data in dataList" ng-change="modifyDropdown(data)">
  </select>
  <label>code</label>
  <input type="text" ng-model="chosenItem['val'].code" disabled/>


  <ul>
    <li>Movie Name</li>
    <li><input type="text" ng-model="name" /></li>
  </ul>
  <ul>
    <li>Name of Director</li>
    <li><input type="text" ng-model="director" /></li>
  </ul>
  <ul>
    <li></li>
    <li><button ng-click="addRow()"> Add Row </button></li>
  </ul>
  <table>
    <tr>
      <th>NO</th>
      <th>Movie Name</th>
      <th>Director</th>
      <th>Industry Code</th>
    </tr>

    <tr ng-repeat="movies in movieLibrary">
      <td><label>{{$index + 1}}</label></td>
      <td><label>{{movies.name}}</label></td>
      <td><label>{{movies.director}}</label></td>
      <td><label>{{movies.code}}</label></td>
      <td><input type="checkbox" ng-model="movies.Remove" /></td>
    </tr>
  </table>

  <div>
    <button ng-click="submitData()">Submit Data</button>
    <button ng-click="removeRow()">Remove Row</button>
  </div>

  <div id="display" style="padding:10px 0;">{{displayInfo}}</div>

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

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Angular JS Changing Values in a Dynamic List

Creating Dynamic HTML with Angular Directives I'm working on code that generates HTML dynamically and includes Angular directives. Since these directives are late-bound, I need to ensure they execute and generate their respective template contents. I ...

Is it necessary to close the browser for jQuery to reload an XML document?

I've successfully used jQuery's $.ajax to retrieve an xml value in my code. However, I'm facing an issue where any changes made to the xml document are not reflected upon a browser refresh. Specifically, the new saved xml value xmlImagePath ...

Updating the information displayed in one section by selecting a button on the Google Maps infowindow located in a separate section

My webpage is divided into multiple divisions. One division contains a map using the Google Maps API with markers. When I click on a marker, an info window opens up. Now, I am attempting to place a button inside that info window which, when clicked, will ...

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Moving a DIV below a fixed-positioned element

I have a website with a scrollable div. It works well, but I also need an absolutely positioned div on top of it - and it still needs to scroll smoothly without any hindrance. You can check out a basic JSFiddle demonstration here: http://jsfiddle.net/41ra ...

Filter jQuery search results for classes with identical names

I am new to using jQuery, so please excuse my lack of experience. My current challenge involves 'getting a reference to an object wrapped in a class', but there are multiple classes with the same name. How can I specifically target and retrieve t ...

Incorporating D3's library functions into Rxjs for seamless integration with Observables

I'm really struggling with this concept and could use some guidance. My goal is to monitor when data is fetched, but I seem to have confused the process. Here's what I've tried so far: Using d3.tsv for an ajax request. var test = Rx.Observa ...

Is it possible to implement validation for the 4th digit of a number before submitting the page by using a combination of ajax and JavaScript

Currently, I am working on a scenario where a postal code needs to be saved and it is a mandatory requirement. I have implemented an AJAX call triggered by the keyup event after entering 4 digits in the postal code field. The AJAX functionality works corre ...

Tips for transitioning the li class from active to none

Struggling with changing the li class (of Home) from 'active' to none (or another class) when clicking on the profile tab, and then changing the li class (of Profile) from none to 'active' when the profile is activated. Snippet of my c ...

Rule: attribute should indicate a specific function

I am currently trying to implement the functionality from https://github.com/rpocklin/angular-scroll-animate in my project, but I keep encountering an error in my console: Error: Directive: angular-scroll-animate 'when-visible' attribute must ...

Developing a Web Application in AngularJS without the use of jQuery

Created a web application with Angularjs and jQueryUI. Curious about the possibility of building the same without using jQuery. ...

Check an image preview prior to uploading through FileReader, rotates the image

After browsing through numerous posts about viewing images before uploading, I stumbled upon an intriguing solution that claimed to be simple using FileReader: function displayImage(input) { if (input.files && input.files[0]) { var reader = ne ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

The Ionic project compilation was unsuccessful

Issue: This module is defined using 'export =', and can only be utilized with a default import if the 'allowSyntheticDefaultImports' flag is enabled. Error found in the file: 1 import FormData from "form-data"; ~~~~~~~~ node ...

Mastering the Vue 3 Composition API: A guide to efficiently utilizing it across multiple Vue instances spread across different files

tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file? I incorporate Vue to improve user interactions on specific pages like t ...

Should private members be kept confidential during program execution?

While Typescript's "private" members may not be truly private at runtime, traditional closures maintain the privacy of their members. Is there value in ensuring that private members remain private during runtime? ...

Reactjs and Redux encounter an Unhandled Rejection with the error message stating "TypeError: Cannot read property 'data' of undefined"

Encountering an error while implementing authentication with react + redux. When attempting to register a user in the redux actions using async / await, I consistently receive this error within the catch block. Here is the snippet of the actions code: imp ...

Ways to transfer a value between two different card elements

I have designed a component with three div cards side by side using bootstrap. The first card displays a list of products, and my intention is that when a product is clicked, the details should appear in the second card on the same page. However, this fun ...

Syntax for the "data" parameter in jQuery.ajax

I am attempting to send the contents of a JavaScript variable to the server for further processing. While I have no issue passing static strings, I encounter a problem when trying to pass a variable containing a string as the WebMethod fails to execute. He ...