What could be causing the malfunction of AngularJS $scope?

I recently started using AngularJS and I'm trying to create an array and send it to the server using the register function. Below is the Controller code snippet:


root.controller('mainController', function($scope) {
    $scope.lineItems = [];
    $scope.addItem = function (id) {
        $scope.lineItems.push(id);
        console.log($scope.lineItems);
        // shows correct data -> Array [ "1", "2", "3", "4", "1" ]
    };
    $scope.register = function () {
        // send data to server
        console.log($scope.lineItems);
        // displays an empty array -> Array []
    };
});

Here are the HTML code snippets and directives used:

<div class="container" ng-controller="mainController">
    <a ng-click="register()"></a>

    <div ng-repeat="product in products">
        <a class="btn" ng-click="addItem(product.id)">Add</a>
    </div>
</div>

The issue arises when I try to invoke the register function, it returns an empty array instead of the array elements present, unlike what happens with the addItem function.

Answer №1

Your code is functioning correctly.

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
  
    $scope.products = [{id:1},{id:2},{id:3},{id:4}];
  
  $scope.lineItems = [];
    $scope.addItem = function (id) {
        $scope.lineItems.push(id);
        console.log($scope.lineItems);
        // displays correct data
    };
    $scope.register = function () {
        // send data to server
        console.log($scope.lineItems);
        // shows an empty array
    };

  
  
});
<div ng-app="testApp" ng-controller="testCtrl">
   <a ng-click="register()">Register</a>

<div ng-repeat="product in products">
    <a class="btn" ng-click="addItem(product.id)">Add : {{product.id}}</a>
</div>
   
</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

Encountering a Issue while implementing caching feature in AngularJS

When I load my modal HTML page for the first time, I get the proper data. However, when I try to load it a second time, an error occurs. Below is my JS code: var cache = $cacheFactory('cacheId'); var cacheData = cache.get('xml'); if ...

Enhancing XTemplate in ExtJS 4.2.1 with dynamic data refresh from store

Here's a situation that's quite unique... A DataView linked to a store is causing me some trouble. In the XTemplate, I want to display the quantity of a specific type of JSON record. Each record has a 'type' property with a value. For ...

Utilizing a parent directive's function within a child directive

Hey there! I'm currently working on creating a pane system where elem.bind('change,...) on a child directive can change the "selected" parent directive. You can check out my progress here: http://plnkr.co/edit/gc35fuUiJVUhHF4QMAwv?p=preview (fun ...

Text flashing in and out of view while utilizing angular translation

I am dealing with a main file and some partials being included in it. I want to access the translated content in both the main file and the partial files as shown below: <p>{{ 'HEADLINE' | translate }}</p> The content translated fro ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

Eliminate various strings by utilizing the replace method

I am attempting to eliminate the words "FC", "AFC" or "London" from a string if they are present. Here is my attempted solution: $scope.teamName = function(url) { return url.replace('AFC'|'London'|'FC', '&a ...

send another response following the completion of the request.end()

I am facing challenges with writing the correct callback function. The situation involves a user making a request to "/city", which then triggers the server to make a request to a third-party service for data retrieval using http.request(). I successfully ...

transferring information from php to json

Below is my JSON script: // add button .click $('a.add').click(function(){ $('#loader').show(); var url = "/?"+$("form[name='jsms_add']").serialize(); ajx = $.ajax({ url: url, type: 'post&a ...

Ensure that it is safe to bypass Vue's built-in sanitization on this specific Vue component for the href attribute

I encountered an issue with a .vue file that contains an anchor tag as shown below: <a class="login_class" :href="loginUrl">Use Universal Login</a> When running Sonar, it raises a warning regarding the :href attribute: En ...

Using jQuery and Ajax to retrieve data from a PHP script's response

As a novice in jquery and Ajax functions, I am working on a website that displays data from a database using PHP. When the edit button is clicked, I want to show the information for each field. I have learned that using ajax is the best approach for this t ...

Delay fading in during the loading process

Recently, I came across a neat animation effect that I would love to incorporate into an upcoming project. The effect involves animating the opacity on load, also known as a fade in. I am curious if it is possible to link multiple elements together (for ...

Access Denied: Origin Issue with OAuth2

I am requesting an authorization code from the OAuth2 Server in order to authenticate a user with my Microsoft App. For more information, I consulted this document. This is my attempt to make the call: function httpGet(){ var theUrl = "https://lo ...

Modifying class selectors does not have any effect on newly added items

Imagine you have a ragged array structured as shown below: var myarray = [ [ ['k1', [] ], ['k2', ['l1', 'l2'] ], ['k3', [] ], ], [ ['k1', [] ], ['k2', ['l1', 'l2&ap ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...

Is it possible to prevent a line break in a div tag, or are there other options available?

On my ASP.NET 4 / VB website, I encountered a scenario where I needed to incorporate a class called "noprint" in my footer, as specified in the print.css file. However, there was already a span class present, so I ended up enclosing div tags around it. Mor ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

What is the best way to conditionally update all subdocuments in MongoDB?

{ _id: UniqueObjectId(), creatures: [ { kind: "dog", IQ: 100 }, { kind: "cat", IQ: 110 }, { kind: "bear", IQ: 120 }, ... ] } What is the best approach to construct an updateOne query in order to mo ...

Unable to execute event.target.blur() function as expected

I am facing an issue with my Bootstrap buttons setup. Here is an example: <button :disabled="page === lastPage" type="button" class="btn btn-default" @click="getPage(lastPage)"> <span class="glyphicon glyphicon-forward"></span> </ ...