Having trouble accessing the selected item in the $scope when using ng-options inside ng-repeat?

I am looking to achieve the following:

I have an array called 'all' that contains all possible items. I want to create a subset of that array and store it in 'subset':

JavaScript (js.js):

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

app.controller('myController', function($scope) {
  $scope.all = [];
  $scope.subset = [{name: 'n1', inUse: false}, {name: 'n2', inUse: false}, {name: 'n3', inUse: false} ];

  // adding new item to 'all'
  $scope.addItem = function() {
    var newItem = {name: '?', inUse: false};
    $scope.all.push(newItem);
  };

  $scope.updateItem = function(index) {
    // index refers to 'all' array
    $scope.all[index].inUse = false;
    $scope.all[index] = $scope.selectedItem;
    $scope.all[index].inUse = true;
  };
});

HTML File (HTML.html):

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="angular-1.4.8.js"></script>
    <script type="text/javascript" src="js.js"></script>
</head>

    <body ng-controller="myController">
        <button ng-click="addItem()">Add Item:</button>
        <div ng-repeat="item in all">
            {{item.name}}
           <select ng-options="item as item.name for item in subset | filter: {inUse: false}" 
                ng-change="updateItem($index)"
                ng-model="selectedItem"></select>
        </div>
    </body>
</html>

However, I am encountering an error 'TypeError: Cannot set property 'inUse' of undefined'. The inUse property seems to be in a child scope. Is this behavior expected? How can I access the selected item within my scope?

I have tried the following approach, but I'm not convinced it's the right way:

var childScope = $scope.$$childHead;
for (var i = 0; i < index ; i++) {
    childScope = childScope.$$nextSibling;
}

$scope.all[index] = childScope.selectedItem;

What is the correct method to achieve my desired outcome?

Answer №1

Charlie, you really inspired me to rethink the way I'm populating my subset:

JavaScript

let app = angular.module('myApp', []);

app.controller('myController', function($scope) {
  $scope.subset = [];
  $scope.all = [{name: 'n1', inUse: false}, {name: 'n2', inUse: false}, {name: 'n3', inUse: false} ];

  // adding a new item in 'all'
  $scope.addItem = function() {
    if ($scope.selectedItem != null) {
        $scope.selectedItem.inUse = true;
        $scope.subset.push($scope.selectedItem);
    }
  };
});

It's not exactly what I had in mind, but it does the job.

HTML

<!doctype html>
<html lang="en" ng-app="myApp">
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="angular-1.4.8.js"></script>
        <script type="text/javascript" src="js.js"></script>
    </head>

    <body ng-controller="myController">
        <select ng-options="c2 as c2.name for c2 in all | filter: {inUse: false}" 
                ng-model="selectedItem"></select>
        <button ng-click="addItem()">Add Item:</ button>
        <div ng-repeat="c in subset">
            {{c.name}}
        </div>
    </body>
</html>

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

What is the best way to calculate the total sum of grouped data using mongoose?

I have a collection of log data that I need to work with. [ { "logType":1, "created_at": 2015-12-15 07:38:54.766Z }, .. .. .., { "logType":2, "created_at": 2015-13-15 07:38:54.766Z } ] My task is to group the ...

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

Utilizing Angular to integrate with an external API

I have encountered an issue while trying to connect to the Expedia API. In order to do so, I need an API key and ID. Initially, I utilized JSONP for this connection but ran into a bug causing problems. Additionally, storing my API key in JavaScript poses ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

VueTablePlus dropdown filter options for Vue.js version 2

I am facing an issue with populating dropdown options on vue good table. My approach involves making an API call to fetch the possible values for the dropdown and then assigning them to the column filter. However, I am struggling to make it work. <vue ...

"Ensure only one checkbox is selected at a time by unchecking the previous

Hi, I'm facing two issues with the code below. The first problem is that when I select checkbox number 3, it automatically selects number 2 as well. I only want this to happen if I manually check it (similar to checkbox number 2). The second issue i ...

"eliminate" ng-if after the condition becomes true

I'm curious to know if it's possible to deactivate or remove ng-if once its value becomes true? In my project, I've constructed a tree structure using a recursive directive. Each branch in the tree has a <div ng-if="visible"> element ...

Types of Data Encoded in Base64

Within an application I am developing, there is a feature for downloading files that are stored as Base64 strings. It is essential to correctly pair the data types with the corresponding files in order to ensure successful downloads. I thought I had sorte ...

"Unlocking the Dialog Box: A Step-by-Step Guide to Programatically Opening Material UI Dialog

Typically, Material UI's Dialog is used as shown below, following the documentation: export default function AlertDialog() { const [open, setOpen] = React.useState(false); const handleClickOpen = () => setOpen(true); const handleClose = () =& ...

Submitting Multi-part forms using JQuery/Ajax and Spring Rest API

Recently, I started exploring JQuery and decided to experiment with asynchronous multipart form uploading. The form includes various data fields along with a file type. On the server side (using Spring), I have set up the code as follows: @RequestMapping ...

JavaScript functions stored in electron

I recently completed a fresh electron application. The application is made up of the following files: index.html main.js renderer.js Inside the index.html file, I included a button with an onclick event: <button onclick="myfunction()">Call Functi ...

Determine the quantity of specific key/value pairs in a dynamic JSON object

I have a data structure in the form of a JSON object that contains key-value pairs for clients. The list of clients varies daily based on their transactions made each day of the month. Therefore, my data only includes transaction information by clients. Be ...

Assign the state to a new object by preserving matching values from the previous state

In my current state, I have an object structured like this: stateObject = {0: 400, 1: 500, 2: 600} Whenever my component rerenders on componentWillUpdate, an additional column is added carrying over the value at key index 0 (400). My goal is to update th ...

Embrace the presence of null values on the client side

When utilizing the code below, I can determine the location of logged-in users. However, there are some users who do not have a specific location assigned. For example, Administrators are common for all locations. In such cases, how can I set it so that ...

The functionality of Next.JS Cpanel Deployment Server.js appears to be malfunctioning

Trying to deploy my website on cpanel, I am utilizing a node.js application with cpanel. Here is the configuration: https://i.sstatic.net/AXap3.png However, when I start my server, it displays "503 service unavailable." https://i.sstatic.net/17JAu.png ...

Switch on the warning signal using bootstrap

How can I make the alert below toggle after 2 seconds? <div class="alert alert-info"> <a href="#" class="close" data-dismiss="alert">&times;</a> Data was saved. </div> ...

I am attempting to input the form data, but all I see on the console is "null" being printed

I am facing an issue where the console.log(data) statement is printing null on the console. I am trying to send the form data (with id "myform") to a Java backend post method, but for some reason the code is not functioning correctly. Can anyone identify ...

Exploring the Potential of jQuery through iBooks

Would like to know how to fix an issue with an interactive glossary I'm creating for an iBooks eBook. When clicking on a term, the definition should appear at the end of the page. Hiding the definition can be done by clicking on the term again or by c ...

What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :) Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain: ipcMain.on("JSON:ShowPa ...

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...