I find it hard to understand AngularJS $scope

I've been struggling with this for hours and could really use some help. I have a .json file containing 100 products structured like this:

[{
    "ean": "3613132010420",
    "brand": "NewBrand",
    "desc": "A description",
    "feature1": "",
    "feature2": "",
    "feature3": "",
    "feature4": "",
    "feature5": "",
    "img": "",
    "metric": {
      "gender": "female"
    },
    "score":""
  },
  {
    "ean": "3613132010420",
    "brand": "NewBrand",
    "desc": "A description",
    "feature1": "",
    "feature2": "",
    "feature3": "",
    "feature4": "",
    "feature5": "",
    "img": "",
    "metric": {
      "gender": "female"
    },
    "score":""
  }]

After reading the JSON using $http and populating $scope.products, everything displays fine in a list. Now, I want to filter the products and update the score variable (after swiping on an option slider).

The view should then reflect these changes due to Angular's data-binding.

But I'm having trouble changing this variable within the $scope. Here's what I've tried so far without success:

$('.find-style-slider .slick-list').bind('touchstart click', function(){
    angular.forEach($scope.products, function(value, key) {

    $scope.products[key].score = '25'; //nothing happens

    var obj = { score: '25' }; 
    $scope.products[key].push(obj); //Uncaught TypeError: undefined is not a function
    $scope.products.splice(key, 0, obj); //no error but $scope variable does not change
    $scope.products[key].unshift(obj); //Uncaught TypeError: undefined is not a function
    });
});

Do I need to call $apply() or make any updates elsewhere? Any help or hints would be greatly appreciated...

Edit: I think there might be an issue with how the $scope works.... I populate the $scope.products with a service:

productService.initDb().then(function(products) {
    $scope.products = products;
});

If I place this

        var obj = { score: '25' };
        $scope.products.splice(0, 0, obj);

INSIDE the initDb function, the first element gets updated! But it doesn't work outside of that scope.

So now the question is: WHY? And how can I access the $scope.products from outside the service function?

I thought the $scope was consistent throughout the controller... confused

Answer №1

$scope.products[key] is actually an object, not an array. The push, splice, and unshift methods are specifically defined for arrays, not objects.

Consider utilizing the following logic:

angular.forEach($scope.products, function(product) {
   product.score = '25';
})

You may also want to try using $scope.$apply() if necessary.

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

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

Exploring the capabilities of Spark DataFrames by handling JSON files with duplicate column names but varying data types

My json data has a version field that differentiates between two formats: file_1 = {"version": 1, "stats": {"hits":20}} file_2 = {"version": 2, "stats": [{"hour":1,"hits":10},{" ...

Error with Ant Design Autocomplete functionality when searching for a number

I am currently using ant design to develop a more advanced autocomplete component that will display data from multiple columns. In this particular scenario, I have two columns named tax_id and legal_name that users can search by. Everything works smoothly ...

Angularjs makes it easy to send multiple GET requests

How can I make multiple ajax calls using different URLs from the football-data.org API? Below is a snippet of my code: angular.module('liveFootball', ['ionic']) .constant('urls', { BASE: 'http://api.football-data.org ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

Manipulate JSON data structure with JavaScript

The initial JSON data: { "data": { "count_at_hub": [ { "hub": "A", "date": "", "size": "1", "count": 141 }, { "hub": "A", "date": "", "size": " ...

Is there a way to verify the existence of an EJS variable?

When working with my Node.js application, I encountered an issue with EJS layout where if the required data is not available in the EJS file, it throws an error. I am looking for a way to add a condition to check for the availability of the EJS variable in ...

How can I enable the "edit" function for a button within a list item?

I am currently working on a feature that allows users to edit list rows by clicking a button. However, I am facing an issue where the "edit" button only edits the first row instead of the matched line. This functionality is part of a program I am developi ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

Tips for distinguishing individual submit buttons within a foreach loop

Here is my code snippet: <?php require_once 'core/init.php'; if($result = $db->query ("SELECT * from countries")) { if($count = $result->num_rows) { $rows = $result->fetch_all(MYSQLI_ASSOC); } ...

AngularJS display element within viewport

My div is extremely wide and contains many elements. I need a way to bring specific elements into view when a button is clicked. Is there an alternative to $anchorscroll that can achieve this? Looking for a solution for horizontally scrolling to a particu ...

Troubleshooting the issue of jQuery Ajax failing to deliver a PDF

I have been attempting to use jquery, ajax, and django to download a pdf file. Here is my code from the views.py file in Django: if request.POST.get('action') == 'download_labels': order_list = json.loads(request.POST. ...

Transforming a JSON structure into a tree model for use with the angular-tree-control component

I need help converting a complex JSON schema into a format compatible with Angular Tree Control. The issue is that the schema does not follow the required treemodel structure for Angular Tree Control, particularly because the children in the schema are not ...

How do I set a new value for a variable from within a function?

After retrieving initial numbers from a JSON file, I want to update them using an ajax call. How do I go about replacing the values of homePoints and awayPoints with the new ones fetched through ajax? I have reviewed the provided answers but none seem to ...

Creating an array in TypeScript involves using the `array` keyword

I'm struggling with either declaring or using a boolean array in Typescript, as I'm not sure where the issue lies. The error message I receive is undefined. Should I be following JavaScript syntax or should I declare a new Array object? Which of ...

Angular $cookieStore failing to hold onto updated cookie when page is refreshed

My current struggle involves $cookieStore's inability to retain a cookie value after it has been updated. Below are two methods from the UserService that handle the cookie: var getCurrentUser = function () { return $cookieStore.get('currentU ...

What measures can be taken to block Javascript from retrieving PHP cookie information?

(Extracted from an interview) Identify the correct answers from the list below: Implement the httponly parameter when creating the cookie The user needs to disable Javascript support This setting is related to cookies in the browser Restrict access to t ...

Errors occurring when trying to parse JSON in Firefox with Firebug, but strangely only happening

Encountering a puzzling error with our application that handles JSON calls. While the app functions flawlessly on various environments and browsers, Firefox presents an issue specifically when run locally. Upon running the code locally, numerous errors occ ...