Refresh ng-repeat following data entry or push in Angular Material dialog

Currently, I am facing an issue with adding a new object to an ng-repeat array. The array is populated with data fetched through an $http request. My goal is to input data in a dialog and pass it to a function that will then add the data as an object to the array, subsequently updating the view. While I can log the input values without any problem and even observe the updated values in the console when logging the array itself, the view fails to reflect these changes. Interestingly, the array updates successfully if I add an object using a button outside of the dialog.

Recent Update

Upon inspecting scopes using Chrome's Angular ng-Inspector, I noticed that the new object gets added to the array within the scope of the controller, which acts as a parent to the element containing the ng-repeat directive. However, the ng-repeat element has its own scope where the array update seems to be missing. It is crucial for me to update this particular array since it is linked to the ng-repeat directive and controls what is displayed on the user interface. The existence of two identical arrays, one reflecting changes while the other doesn't, remains puzzling. When pushing the object onto '$scope.plots', my aim is to target the scope of the ng-repeat parent element. Finding an effective method to achieve this is still an ongoing challenge for me.

Dialog Implementation

function showAdd(ev) {
        $mdDialog
            .show({
                controller: DialogController,
                templateUrl: '/templates/addDialog.html', //includes inputs associated with values used in the push function below. Pressing a button invokes addPlant()
                targetEvent: ev,
                clickOutsideToClose: true,
                openFrom: 'left'
            }).then(function(added) {
                newPlant(added);
        })
    }

Dialog Controller Setup

function DialogController($scope, $mdDialog, $http) {
$scope.addPlant = function (added) {
    for (var i = 0; i < added.quantity; i++) {
        $http.post('/addPlant', added).then(function () { //solely responsible for posting data to a database, not directly related to the current issue.
                $mdDialog.hide(added);
            }
        });
    }
};

The Function for Pushing Data

var newPlant = function(added) {
        $scope.plots.push({
            'plot': added.plot,
            'varieties': [{
                'count': added.quantity,
                'variety': added.variety
            }],
            'count': added.quantity
        });

Answer №1

In order to handle the situation, I had to develop a service and send out the newly added object through rootScope broadcasting. Additionally, I set up a separate controller specifically for the ng-repeat element to catch the broadcast.

Upon closing the dialog window, the promise is fulfilled by passing the form data to the service.

$mdDialog
        .show({
            controller: 'DialogCtrl as dc',
            templateUrl: '/templates/addDialog.html',
            targetEvent: ev,
            clickOutsideToClose: true,
            openFrom: 'left'
        }).then(function(added) {
            addPlant.prepForBroadcast(added) //invoking the service within the promise and passing input values of 'added'
    })

A dedicated service was implemented to broadcast the object

var myApp= angular.module('myApp');

myApp.factory('addPlant', ['$rootScope', function($rootScope) {
    var box= {}; //I prefer to refer to the main factory object as a 'box'
    box.newPlant = {};

    box.prepForBroadcast = function(added) {
        box.newPlant = added;
            this.broadcastItem();
    };

    box.broadcastItem = function() {
        $rootScope.$broadcast('broadcast');
    };
    return box; //sending out the box containing newPlant
}]);

Also, a distinct controller was set up for the ng-repeat element to listen for broadcasts

myApp.controller('ListCtrl', ['$scope','addPlant', function($scope, addPlant) {

$scope.$on('broadcast', function() { //listening for broadcast
        $scope.plots.push({
            'plot': addPlant.newPlant.plot,
            'count': addPlant.newPlant.quantity,
            'varieties': [{
                'variety': addPlant.newPlant.variety,
                'count': addPlant.newPlant.quantity
            }]
        });
    })
}]);

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

Is it possible to determine if child_process has finished in node.js?

I'm currently in the process of developing a cakefile with node.js and I need to determine whether a child_process has completed before proceeding to the next one. {exec} = require 'child_process' exec 'casperjs test.js', (err, s ...

What is causing ui-route to fail in resolving state1 when transitioning from state2?

I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...

Solving yarn conflicts when managing multiple versions of a package

My software application contains a vulnerability related to a package that has different versions available (1.x, 2.x, 3.x). Since many other packages rely on this particular one as a dependency, updating each one individually is not a viable solution at t ...

What strategies can be used to efficiently perform Asynchronous Operations on a high volume of rows in a particular database table?

I am looking to perform Asynchronous Operations on every row of a specific database table, which could potentially contain 500,000, 600,000, or even more rows. My initial approach was: router.get('/users', async (req, res) => { const users = ...

JavaScript: create a button that dynamically changes size and color when scrolling

I have a pulsing button (#scrollarrow) at the bottom of my website that disappears as I start scrolling. The jQuery code responsible for this effect is as follows: $(document).ready(function(){ $(window).scroll(function(){ if ($(thi ...

Implementing timeAgo with jQuery (or a similar tool) to display the elapsed time since a user (client) accesses or updates a webpage

Currently, the timer displayed always shows the actual time instead of phrases like "about a minute ago" or "5 minutes ago". I have tried different solutions without success. //timeago by jQuery (function timeAgo(selector) { var templates = { pref ...

Is it necessary to handle asp.net mvc apicontroller requests asynchronously in conjunction with angular $resource?

I'm currently utilizing asp.net mvc ApiControllers for my backend services and an Angular frontend using $resource. Should I implement the asp.net mvc async pattern as well? While I am aware that $resource is asynchronous and doesn't interfere w ...

Setting a value for the identifier just one time

I've been grappling with an issue that's been on my mind for some time now. There are 14 divs on my webpage, and I need each one to be given a random ID (ranging from 1 to 14) every time the page loads. These divs all share the class ".image-box ...

React is a powerful tool that allows for the dynamic changing of state within

Struggling with my first React app and trying to accomplish something basic. The Input component in my app has an array in state, which sends two numbers and a unique ID as an object to a parent Component when the array has two numbers entered. Sending t ...

The button must be programmed to remove a specific item from the server

I am currently developing an application to monitor my expenses using javascript, nodejs, express, and handlebars as the templating engine. Within the app, I have a "list" div that displays all of my expenses. (There is an add button next to the list, not ...

MUI: Issue with pseudo element appearing cropped outside of Paper container

I am facing an issue where a red arrow pseudo element '::before' is partially cut off outside its container '.MuiPaper-root'. I need the arrow to remain visible, any suggestions on how to fix this? Here is the relevant code snippet and ...

Implement pagination once the amount of data surpasses the specified threshold

I'm looking to implement pagination once the displayed data exceeds a certain limit. Currently, I have set it up so that only 6 items are shown at a time. What I want is to add pagination below the table to display the remaining data. How can I achiev ...

Navigating to a specific element following an AJAX request

Can't seem to get the page to scroll to a specific element after an ajax call. What could be causing this issue? index.php <style> #sectionOne { border: 1px solid red; height: 100%; width: 100%; } #sectionTwo { border: 1px solid blue; heigh ...

Discover the power of utilizing the reduce function to extract the value of a specific field within an array of Objects

In the following example, we have an object with 3 forms: formA, formB, and formC. Form A and B are objects, while formC is an array of objects that can contain multiple items. const object: { "formA": { "details": {}, ...

Angular Custom Pipe - Grouping by Substrings of Strings

In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe impleme ...

Having trouble implementing object type switching in Typescript

While in the process of developing an angular application, I stumbled upon a peculiar issue. Some time ago, I crafted this piece of code which performed flawlessly: selectedGeoArea: any receiveStoreEvent(event) { switch (event.constructor) { ca ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...

Complete a submission using an anchor (<a>) tag containing a specified value in ASP.Net MVC by utilizing Html.BeginForm

I am currently using Html.BeginFrom to generate a form tag and submit a request for external login providers. The HttpPost action in Account Controller // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public Acti ...

The ui-routing function in $state.go fails to recognize custom parameters

I've implemented a 'go' back feature that redirects the user to the advSrch screen/state. If I set loadSearchQuery to true, it should load the search query. $scope.back = function() { $state.go('advSrch', { isDeleted: false, ...

PHP and JavaScript: Understanding Variables

I currently have a View containing an Associative Array filled with information on accidents. Users will have the ability to click on a Country. Once clicked, I want to display accident-related data for that specific country. This data is pulled from PHP ...