Issue Arises in AngularJS where $scope values are not properly updating after ng-repeat loop

I am utilizing a controller that holds data to be iterated through using ng-repeat, and I am using it in conjunction with this selection model directive.

However, once I use ng-repeat to generate multiple entries in the DOM, the bindings to $scope.selectedItems cease to function.

While I am aware that ng-repeat creates a new child scope for each iteration, I am puzzled as to why the updates to the selectedItems property are not being recognized in the MyController.

Controller:

(function() {
    angular.module('myModule', ['product.module'])
        .controller('MyController' ['$scope', 'SomeService' function($scope, ProductService) {
            $scope.selectedItems = [];
            $scope.productService = new ProductService()  //constructor pattern object
            $scope.products = $scope.productService.items;

            $scope.productService.fetchData(); //grabs data from server and sets the productService.items to an array of objects                
        }]);
})();

HTML

<div ng-controller="MyController">
<ul>
    <li ng-repeat="product in products"
        selection-model-type="checkbox"
        selection-model-mode="multiple"
        selection-model-selected-items="selectedItems">
        {{product.name}}
    </li>
</ul>


<div ng-controller="MyController"> <!-- this binding doesn't work after the ng-repeat takes place -->
    There are {{selectedItems.length}} products
</div>

Answer №1

productService.items could consistently reference the same instance, but selectedItems will always vary. To ensure consistency, utilize a single controller or move selectedItems to a service.

<div ng-controller="MyController">
<ul>
    <li ng-repeat="product in products"
        selection-model-type="checkbox"
        selection-model-mode="multiple"
        selection-model-selected-items="selectedItems">
        {{product.name}}
    </li>
</ul>

    Currently, there are {{selectedItems.length}} products selected
</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

Troubleshooting Issue with Angular's ng-view Implementation

I have been following a tutorial on setting up a MEAN stack single-page application with the URL provided. However, after setting up the application, the views are not displaying in the ng-view div as expected. Here is the structure of my app: - app ---- ...

How can one generate a custom link using vue-router in Vue.js after the rendering process has been completed?

Currently, I am utilizing VUE and I must say, boostrap-table is performing admirably! Within my component, I have the following: <BootstrapTable :columns="table.columns" :data="table.data" :options="table.options"></ ...

Ways to Export HTML to Document without any borders or colorful text

How can I make a contentEditable area visible when filling text and then disappear when exporting the document? I found a script online that allows you to do this, but the issue is that the contentEditable area is not visible until clicked on. To address t ...

Narrow down JSON file data by a particular value with the help of AngularJS

Here is the current structure of my JSON file: [ { "name":"Bánh bao nướng phô mai thịt", "image":"banhbaonuongphomaithit", "howtocook":"<h1>abc</h1>", "video":"sY6bswxfVGM", "category": "bakery" }, { "name" ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

XAMPP web service encounters issue with unregistered Angular controller

I encountered the following error message: Error: $controller:ctrlreg A controller with this name is not registered. Despite loading all my scripts and adding them to index.html, the error persists. Click here to verify that all scripts are loaded Below ...

Optimal method for showcasing a large 2-dimensional array

I am considering displaying a 1000x1000 array with elements that are either black or white based on boolean values. I am contemplating using either javascript or winforms for this task, but I want to understand the potential drawbacks of each option befo ...

Guide to building an HTML table using an array of objects

Is there a way to dynamically create a table from an array of objects? Here's an example array: let data = [{name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3}] The desired HTML output shou ...

"Troubleshooting when a NodeJS Program Refuses to

Currently facing an issue while attempting to execute a Node program written in JavaScript with no indication of what's causing the problem. The program abruptly ends without providing any error or stack trace. const prompt = require('prompt-sync ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

Arrange the array in chronological order based on the month and year

I'm looking for assistance with sorting an array by month and year to display on a chart in the correct order. Array1: ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'....]; Desired Output: ...

ag-Grid - Automatically adjusting the height of detail section when data updates

I have implemented a table with a Master/Detail setup and I am utilizing the getRowHeight callback. Initially, the row height is set correctly. I expect that when the table data is updated, the row height for rows containing a detail grid should be recalc ...

Exploding particles on the HTML5 canvas

I've been working on a particle explosion effect, and while it's functional, I'm encountering some issues with rendering frames. When I trigger multiple explosions rapidly by clicking repeatedly, the animation starts to lag or stutter. Could ...

What is the process for using Selenium and Java to upload a file via an 'input' element with the type "hidden"?

I am facing a challenge with using Java Selenium to upload a file in the input element provided (upload element). <input type="hidden" ng-model="model[options.key || index]" id="formly_21_fileupload_args_content_substrate_surface_media_document ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Is it possible to avoid passing each individual Vue prop by destructuring them?

Essentially, I am working with a component <Device> v-for="device in devices" :key="device.name" :device="device" :name="device.name" :number="device.number" :type="device.type" :status=&qu ...

When the file is sent to the server, PHP may not receive any data in $_FILES

Looking to implement file uploading using https://github.com/danialfarid/ng-file-upload/. I have encountered an issue when trying to retrieve the uploaded file using the global array $_FILES. It appears that while the file content is successfully sent to t ...

Tips for generating an ecosystem.json file for a node.js express app with pm2 that launches with npm start command

I am looking to utilize pm2 for my node.js express app. Although I can successfully start the server using npm start, I want to set it up in the ecosystem.json file so that I can manage it with pm2 and run it in cluster mode. One thing to note is that I c ...

When invoking a function using ng-init within ng-repeat, only the final item in the iteration yields a result

My goal is to update the content of a progress bar for each row in a table using ng-init within ng-repeat. Here is my code snippet: The code snippet for the view section is as follows: <tr ng-repeat-start="p in projetsListe" ng-init={{progressBar($in ...

What steps do you need to take in order to transform this individual slideshow script into numerous slideshows

I came across this code online that effectively creates a slideshow. https://css-tricks.com/snippets/jquery/simple-auto-playing-slideshow/ Is there a way to modify the code to support multiple slideshows? I've made several attempts without success ...