Unable to append a string to an array within a $scope function using AngularJS

I've been encountering an issue where I can't seem to add my jaddString to my array. Even though the string is created, it doesn't get added to the array. When I check my console in Google Chrome, I receive the following error: ReferenceError: aa is not defined

Here's the JavaScript code snippet:

var app = angular.module('kompileApp', []).controller('partsList', function($scope){
this.aa = addedArray;
this.aaString = addedArrayString;
this.jaddString = justAdded;

$scope.jadd = function(partId){
        jaddString = parts[partId - 1].id + ': ' + parts[partId - 1].name + ', ' + parts[partId - 1].price;

        aa[partId - 1] = jaddString;
    };
});
    
// Array of parts
[
{
id: 1,
name: 'vitamine A',
price: 3,
canAdd: true,
added: false,
comp: '2, 5'
},
// Additional parts here...
];

var addedArray = new Array(parts.length);

var justAdded = '';

In my HTML file, I call the function within ng-click like this:

<div ng-controller="partsList as pl" class="ctrlDiv">
<li ng-repeat="part in pl.parts | orderBy:'+price'" ng-hide="part.added || !part.canAdd" class="plLi">
<button ng-click="jadd(part.id); pl.aa[part.id] = pl.jaddString" ng-show="part.canAdd" class="plistbutton">add</button>
</div>
</div>

I noticed that if I manually assign a value to my array, it displays correctly on my HTML page:

var addedArray = new Array(10);
addedArray[0] = 'lalala'

Answer №1

To access the this object in the jadd function, you should create an alias for it.

For example:

var app = angular.module('kompileApp', []).controller('partsList', function($scope){
{
   var self = this;
   self.aa = addedArray;
   self.aaString = addedArrayString;
   self.jaddString = justAdded;
   $scope.jadd = function(partId){
      self.jaddString = parts[partId - 1].id + ': ' + parts[partId - 1].name + ', ' + parts[partId - 1].price;
      self.aa[partId - 1] = self.jaddString;
};
});

Answer №2

To clarify, instead of using $scope.jadd, utilize this.jadd and update the ng-click function to cl.jadd. It's best practice to keep this and $scope separate. Additionally, it is not implicit in JavaScript. I suggest implementing the following:

this.jadd = function(partId){
    this.jaddString = parts[partId - 1].id + ': ' + parts[partId - 1].name + ', ' + parts[partId - 1].price;

    this.aa[partId - 1] = jaddString;
};

});

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

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

Tips on showing a response in an HTML node with Node.js and AngularJS

Just starting out with NodeJS and AngularJS. My goal is to fetch a response from an external site and display it in Angular JS. I managed to send the request and receive a response, but on the UI JSON appears as a string with forward slashes "\". For ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

jQuery: Function is not running as expected

I'm facing a challenge in executing a function twice, and I'm having trouble identifying the issue. Check out my JSFiddle at the following link: http://jsfiddle.net/g6PLu/3/ Javascript function truncate() { $(this).addClass('closed&apo ...

Using JavaScript to access the Wikipedia API with the Access-Control-Allow-Origin feature

Currently attempting to retrieve a response from the Wikipedia API on Codepen. The expected reply should be in json format, which I plan to display using console.log. However, when checking the console, I encounter an error: Cross-Origin Request Blocked: ...

Dynamically incorporating a new carousel element using JavaScript within Onsen UI 2

Attempting to dynamically add a new carousel item using JavaScript in Onsen UI 2, but encountering an issue. Below is the code being used: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <link ...

Disorder in an array

Hey there! I am looking to fetch 3 keys from $arr where the value of $arN[0] is higher than the others... Here's the code: $ar1=array(201,281); $ar2=array(1252760,1359724); $ar3=array(452760,34349724); $ar4=array(1260,134344); $ar5=array(232750,135 ...

AngularJS - Navigate to a specific page with an item already chosen

I'm currently working on a project with a page layout similar to the one in this plnkr example. http://plnkr.co/edit/NKVVn4ga6lYOBWEblt0o?p=preview One of the requirements I have is when clicking on a specific hyperlink at the bottom of the page wit ...

JQuery and Fancybox causing issues when triggered on Internet Explorer 8

I am experiencing an issue with my jQuery code on my webpage. It works perfectly fine in Chrome, but I encounter an error in Internet Explorer 8 specifically in the trigger('click') line. $('#btnd16').click(function(e){ var iiid = ...

Oops! Looks like you forgot to include the "reducer" argument. It is necessary and should be either a function or an object of functions that can be passed to combineReducers

1 I'm currently working through the Redux tutorials on their website and I'm encountering an issue when trying to use combine reducers. When I run my code without using combine reducers, everything works fine. However, as soon as I include the s ...

Execute code after the CSS has been loaded, but before the images start downloading

My website is experiencing a challenge. Downloading images is taking too long, with the complete website taking around 20 seconds to fully load on my system. A loader is displayed but only hides once the complete website is loaded (after 20 seconds). Whe ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

"React-router is successfully updating the URL, however, the component remains un

I am currently working on a React application that includes a form for users to fill out. Once the user clicks the submit button, I want them to be redirected to a completely different page. Although I have only focused on the visual design at this point a ...

The Impact of Using Custom HTML Tags with AngularJS Directives

If I were to create a unique avatarDirective in AngularJS that is connected to an userEmail property on the scope. The directive would update this HTML … <avatarDirective userEmail="user.email" /> with a standard img tag that has its src attribut ...

What is the best way to combine an additional array into a different project attribute?

There are 2 arrays being used. This is the content of userGroups: console.log(this.items) [ { "id": 63, "name": "URLGROUP-1643836551908" } ] The contents of urls are shown below: userGroup can contain ...

The directive code takes precedence over the controller code and is executed first

A custom directive has been implemented and is utilized as shown below: <div car-form car="car" on-submit="createCar(car)"></div> This directive is used on both the new and edit pages, each with its own controller. The EditCarController retri ...

What is the best way to retrieve data from a database using AngularJS?

Can AngularJS be used to perform database queries? What is the recommended approach for achieving this task? While I know it can be done on a PHP Server, is it also feasible on a SQL Server? ...