Unable to add an object to an array using a forEach loop in Angular

I'm attempting to input a color name and if the color isn't already in the list, it should be added and the li element should also display that color. I can't figure out what's going wrong here.

  <!DOCTYPE html>
    <html>
        <head></head>
        <body ng-app="colors">
        <div ng-controller="mainCtrl as ctrl">
        <ul ng-repeat="color in ctrl.colors">
            <li ng-bind="color.label" ng-style="{color:color.label}">
        </ul>
        <input type="text" ng-model="ctrl.colordisp"></input>
            {{ctrl.colordisp}}
        </div>
        <button type="button" ng-click="ctrl.checkColor()">submit</button>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <script>
        angular.module("colors",[])
            .controller("mainCtrl",[function(){
            var self=this;
            self.colors=[
            {label:"red"},
            {label:"blue"},
            {label:"green"}
            ];
            self.colordisp="red";
            self.checkColor=function(){
            angular.forEach(self.colors,function(c){
                if(c.label!==self.colordisp){
                    self.colors.push("label:"+self.colordisp);
                }
            });
            };
            }]);
        </script>

        </body>
        </html>

Answer №1

You seem to be encountering a few issues.

Problem #1. Make sure to place the ngClick button within the controller container for it to function properly:

<div ng-controller="mainCtrl as ctrl">
    <ul ng-repeat="color in ctrl.colors">
        <li ng-bind="color.label" ng-style="{color: color.label}">
    </ul>
    <input type="text" ng-model="ctrl.colordisp"> {{ctrl.colordisp}}
    <button type="button" ng-click="ctrl.checkColor()">submit</button>
</div>

Problem #2. Remember to push an object into the array, not just a string:

self.colors.push({label:  self.colordisp});

Problem #3. Your method of checking for object existence in the array is currently incorrect. Consider using either Array.prototype.filter or Array.prototype.some:

self.checkColor = function() {
    var inArray = self.colors.some(function(obj) {
        return obj.label === self.colordisp;
    });
    if (!inArray) {
        self.colors.push({label:  self.colordisp});
    }
};

And one final note: remove </input> - input elements do not require closing tags since they do not have content.

Check out a demo: http://plnkr.co/edit/LBy5RCiXYApBEvuUoIdj?p=preview

Answer №2

Make sure you are not adding a string, but an object instead.

Revise the following code block:

self.colors.push("label:" + self.colordisp);

to:

self.colors.push({ label: self.colordisp });

Your current logic is incorrect. You need to verify if the color already exists before adding it. Here's an example of how to do it:

self.checkColor = function() {
  var found = false;
  angular.forEach(self.colors, function(c) {
    if (c.label === self.colordisp) {
      found = true;
    }
  });
  if (!found) {
    self.colors.push({ label: self.colordisp });
  }
}

This updated approach should resolve the issue.

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

AngularJs Redirect

Here is the code snippet I'm working with: $scope.insertTodo = function(){ TodoService.post($scope.todo); $location.path("/#/"); } The intention is for it to execute TodoService.post() and ...

Controller variable in Angular not being updated in view

I am facing an issue with my Angular view not updating after changing a value in the controller through a partial. Interestingly, when I use console.log to log the changed values, everything seems to work fine. TestController $scope.testitem = 0; $sco ...

Which codec strings are considered valid for the web codecs API?

I am searching for a definitive list of valid strings that can be passed as the `codec` parameter in `VideoEncoder.isConfigSupported({ codec, width, height })`, but I have been unable to find a clear answer so far: The TS declaration file states that it m ...

Tips for extracting form data from a directive in Angular

I am using this template setup: <div class="modal" id="popupModal" tabindex="-1" role="dialog" aria-labelledby="createBuildingLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <d ...

Uib-tabset - update triggered by successful HTTP response

I am implementing a modal box with tabs. The first tab allows users to select items and assign them to a user when they click the "Next" button. Upon successful assignment, the next tab automatically displays the configuration for those items. If there is ...

The file transfer functionality in object FileTransfert is malfunctioning on certain Android devices when attempting to upload

A mobile application was created to facilitate the sharing of items. Users are required to provide information about the item they are sending, along with the option to add a picture of the object. To achieve this functionality, plugins such as cordova f ...

`Incorporate numerous models into a For Loop for efficient processing`

Currently, my goal is to: Retrieve a JSON file from the server that contains data regarding my models Utilize a PLY loader within a for loop to incorporate them into the scene Include them in an array Below are the functions I've implemented: func ...

Error message: Attempting to access the 'props' property of an undefined variable

Trying to establish communication between a child and parent component using props has presented a slight issue. An error is encountered when attempting to utilize the StatusChanged() function. The parent file (App.JS) looks like this: class App extends ...

Unable to modify the styles of nested Material UI components

I am currently customizing the styles of the card and cardContent components in material ui. I have implemented them within functional components and am facing an issue with overriding the root style of each component. Specifically, I am struggling to modi ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Timeout for asynchronous scripts

Recently diving into the world of Protractor and trying out Protractor-net. Encountering an "Asynchronous script timeout: result not received in 0 seconds" error when executing Protractor-net scripts. If you're curious about Protractor-net, check it ...

Utilizing Promises with Chained .then() Functions

I am struggling with simplifying the readability of my code. I have separated it into two main functions, but I am still dealing with nested .then() statements. I am looking for advice on how to structure these functions more effectively. It is important ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

JavaScript - Calculate the streak of consecutive work days

Consider this array of plans: [ { _id: "1", project_id: "1", day: "2021-03-02" }, { _id: "2", project_id: "1", day: "2021-03-01" }, { _id: "3", project_id: "1", day: "2021-03-03" }, { _id: "4", project_id: "2", day: "2021-03-01" ...

Looking to fill every space? Try using React with MUI Grid!

I am currently using Material UI Grid to create an image grid, and I am facing challenges in eliminating the gaps between certain grid items. Despite attempting to modify the alignitems and justify values of the container, I have not been successful in r ...

Instructions for applying a specific style to TextFields using a theme provider

Custom transitions and colors have been added to the textfields using the makeStyles hook in the component. The issue lies in needing to define these customs every time they are used in a component. There is a desire to establish them in the theme provid ...

What could be the reason for the Puppeteer script returning 'undefined' when using ExecutionContext.evaluateHandle()?

Currently, I am in the process of learning the Puppeteer API with version 1.9.0. Below is the code I am using to click a button within an iframe: const changePrefsFromAllToNone = async () => { try { const browser = await puppeteer.launch ...

Tips for avoiding errors caused by chart adjustments in Angular.js

I have two different perspectives, view A and view B. In view A, I present my chart. However, upon transitioning to view B, I encounter a quick error. It seems that this error arises due to a setTimeout function not being completed before the view change o ...

Google Maps markers are not being populated with the accurate geoJson data

The markers linked to my geoJSON are not showing up on the map. When I test my geoJSON on , it works perfectly. However, if I replace my geoJSON with a sample from the Google Maps Dev API 'https://storage.googleapis.com/maps-devrel/google.json', ...

Testing the existence of Angular routes: Verifying the presence of a specific route

When setting up navigation, I am looking to include a button only if a certain route is accessible or a specific permission exists. I have sorted out the permissions aspect, but now I want to exclude pages based on configuration settings. It would be helpf ...