Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template:

<body ng-controller="myCtrl">

     {{loadDataSubject('${subjectList}')}}
     {{loadDataTopic('${topicList}')}}



<h1 class = "bg-success" style="color: red;text-align: center">Fill in the below details for Question Template : -</h1> <br> 

<div class="container">

  <form method="get" action="createTemplate">
    <div class="form-group">

    <label for="sel1">Topics (select one):</label>
     <select class="form-control" ng-model="selectedTopic" ng-options="topic.name as topic.name for topic in topics">
    </select> <br>

    {{selectedTopic}}

      <label for="sel1">Subject (select one):</label>

     <select name="subject" value= "" class="form-control" ng-model ="selectedSubject" ng-options="sub.name as sub.name for sub in subjects">
    </select> 
    <br>

      <label for="sel1">Negative marking:</label>
      <select class="form-control" name="negativeMarks">
        <option>Yes</option>
        <option>No</option>
      </select> <br>

      <label>Reference Book:</label>
       <input type="text" class="form-control" name="ref" required>
      <label for="sel1">Number of Questions:</label>
       <input type="number" class="form-control" name="questionCount" required><br>

       <input class ="bg-primary" type="submit" value="submit and download template">

    </div>
  </form>
</div>


</body>

and here is the JavaScript code for AngularJS functionality:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {

    $scope.subjects = [];
    $scope.topics = [];
    $scope.selectedSubject = {};
    $scope.selectedTopic = {};


    $scope.loadDataSubject = function(subjectList) {
          $scope.subjects = JSON.parse(subjectList);
        };

    $scope.loadDataTopic = function(topicList) {
          $scope.topics = JSON.parse(topicList);
        };  
});

I am trying to add a filter to only select the subjects related to the selected topic, using something like this: filter : selectedTopic.id

The error I'm encountering is:

angular.js:38 Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.8/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…turn%20b(f%2Cc%2Ce)%7D%22%2C%22newVal%22%3A74%2C%22oldVal%22%3A68%7D%5D%5D
    at angular.js:38
    at r.$digest (angular.js:15934)
    at r.$apply (angular.js:16160)
    at angular.js:1679
    at Object.e [as invoke] (angular.js:4523)
    at c (angular.js:1677)
    at yc (angular.js:1697)
    at Zd (angular.js:1591)
    at angular.js:29013
    at HTMLDocument.b (angular.js:3057) 

Prior to that, I also want to bind the value of an object to ng-model, while displaying the object's name. Any guidance on how to achieve this would be greatly appreciated as I am new to AngularJS.

Available subjects are: [{"subjectId":1,"name":"ComputerScience","code":"CS"},{"subjectId":2,"name":"Computer Basics","code":"CS","documentUrl":"None"},{"subjectId":3,"name":"Computer Basics","code":"CS","documentUrl":"None"},{"subjectId":4,"name":"php","code":"PHP01","documentUrl":"None"},{"subjectId":5,"name":"JAVA","code":"JAVA01","childSubjects":[{"subjectId":6,"name":"Core Java","code":"JAVA02","parentSubject":5,"childSubjects":[{"subjectId":8,"name":"Thread","code":"JAVA04","parentSubject":6},{"subjectId":9,"name":"Object Class","code":"JAVA05","parentSubject":6},{"subjectId":10,"name":"Inheritance","code":"JAVA06","parentSubject":6}]},{"subjectId":7,"name":"Advance Java","code":"JAVA03","parentSubject":5,"childSubjects":[{"subjectId":11,"name":"Servlet","code":"JAVA07","parentSubject":7}]}]},{"subjectId":12,"name":"Computer Basics","code":"CS","documentUrl":"None"}]

Available topics are:

[{"topicId":1,"name":"Technical","code":"TECH","isSubjectsRelated":1,"description":"All Technical subjects","isActive":1,"subjects":[{"subjectId":1,"name":"ComputerScience","code":"CS"},{"subjectId":1,"name":"ComputerScience","code":"CS"}]},{"topicId":2,"name":"GATE","code":"GATE","isSubjectsRelated":1,"description":"GATE exam","isActive":1,"subjects":[]},{"topicId":5,"name":"Programming","code":"PROG","isSubjectsRelated":0,"description":"Coding skills","isActive":1,"subjects":[{"subjectId":5,"name":"JAVA","code":"JAVA01"}]}]

Answer №1

Update your Topics dropdown menu like this

<label for="sel1">Choose a Topic:</label>
     <select class="form-control" ng-model="selectedTopic" ng-options="topic as topic.name for topic in topics">
    </select>

Do the same for the subject dropdown menu. You can find an example on this website.

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

jQuery: add to either element

What is the most efficient way to use .appendTo for either one element or another based on their existence in the DOM? For instance, I would like to achieve the following: Preferred Method: .appendTo($('#div1') || $('#div2')); Less ...

Exploring the realm of styling with React JS

Currently, I am facing an issue while working with material-ui for my web design. Here is the code snippet that I am using: const useStyles = makeStyles((theme) => ({ card: { marginTop: theme.spacing(10), direction:"column", alig ...

Issues with hover functionality in React Material Design Icons have been identified

I'm facing an issue with the mdi-react icons where the hovering behavior is inconsistent. It seems to work sometimes and other times it doesn't. import MagnifyPlusOutline from "mdi-react/MagnifyPlusOutlineIcon"; import MagnifyMinusOutli ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

Activating a link click inside a table with jquery

I have been attempting to trigger a click on an anchor within the table compareTable with the code below, however it does not appear to be working as expected. Would anyone be able to provide insight into a possible solution? $('#compareTable a' ...

Verify MVC Controller Authorization and respond with 401 Unauthorized to the AngularJS application

Currently, I have an AngularJS application that interacts with an MVC Controller to retrieve specific data. To ensure that users have the necessary permissions to execute certain actions on the controller, I've created a custom class called RBACAutho ...

Generating an array of objects using Jquery from XML data

I need assistance with extracting data from XML text nodes stored in a variable and then creating an array of objects using jQuery. The XML data I have is as follows: var header = ['name', 'data1', 'data2']; var data = &apos ...

Preparing JSON data for creating a wind map with Leaflet

I am currently working on converting netCDF data to JSON in order to use it with leaflet-velocity. This tool follows the same format as the output of grib2json used by cambecc in earth. An example of sample JSON data can be found at wind-global.json. By u ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

Steps to display a NotFound page when the entered path does not match the route in module federation React micro frontends

Typically, if the provided path does not match, we display the NotFound page to the user using the following code snippet <Route path={"*"} component={NotFound} /> However, upon adding this code, I always get redirected to the home page ( ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

CoffeeScript equivalent of when the document is loaded

Recently, I've been delving into Coffeescript for my web application, but I'm encountering a frustrating issue. The methods are not being called until I manually reload the page. I suspect that the missing piece may be the $(document).ready(func ...

The cookie being sent from the backend API (implemented in nodeJS using express) to the frontend (developed with NextJS) is not successfully setting in the

I'm currently working on a NextJS app running on localhost:3000 and a node express API running on localhost:3030. I have encountered an issue where, after sending a request from the frontend to the backend login route, I am trying to set a cookie call ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Tips for implementing a jQuery script within an Angular directive

I recently attempted to incorporate a jQuery code into an Angular component, but I encountered some issues. The jQuery code was originally placed in the HTML, which is considered bad practice. So, I tried creating a new function and adding my jQuery code t ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

What could be causing the page to automatically scroll to the bottom upon loading?

My experience with this bootstrap/jquery page in Firefox (v39, latest updates installed) has been unusual as it always seems to jump to the bottom of the page upon clicking. Upon inspecting the code, I couldn't find any JavaScript responsible for thi ...

Encountering SCRIPT1014 and SCRIPT1002 errors within an Angular4 application when using Internet Explorer 11

My Angular 4 application runs perfectly in various browsers. However, when trying to launch it in Internet Explorer version 11, I encounter the following two errors: SCRIPT1014: Invalid character addScript.js (9,1) SCRIPT1002: Syntax error main.bundle.js ...