AngularJS: How to manipulate DOM with JSON objects created by controllers after the initial load

It seems that I may not be following the "Angular Way" as I cannot find similar use cases in the documentation.

In my code, I have an input that takes comma-separated inputs and triggers a function through ng-submit within the weatherController:

$scope.submit = function() {    

    var rawZipString = this.text;
    var strippedString = rawZipString.replace(/\s+/g, '');
    var zipArray = strippedString.split(',');

    for(i=0;i<zipArray.length;i++){
        Weather.getWeatherForecast(zipArray[i])
        .then(function(forecast){
            $scope.temperatures.push(forecast);
        })
    }

    /** Create weather objects */
    for(i=0;i<$scope.temperatures.length;i++){
            var tempForecast = new weatherConstructor(zipArray[i],$scope.temperatures[i]);
            $scope.zipForecast.push(tempForecast);
        }

    /** Format as JSON */
    $scope.DOMdata = angular.toJson($scope.zipForecast);
        console.log($scope.DOMdata);    
    }

This is how weatherConstructor is defined:

function weatherConstructor(zip,temp){
    this.zip = zip;
    this.temp = temp;
}

I am unsure of how to render the constructed JSON object ($scope.DOMdata) in the view, which has the following structure:

<div ng-controller="weatherController">
<h4 ng-repeat="DOM in DOMdata">
    {{DOM.zip}} now is {{DOM.temp}}
</h4>   

Answer №1

When working with HTML, make sure to utilize both ng-model and ng-list to effortlessly convert comma-separated values into an array.

<input type="text" ng-model="text" ng-list>
<div ng-controller="weatherController">
<h4 ng-repeat="DOM in DOMdata">
  {{DOM.zip}} now is {{DOM.temp}}
</h4>

For JavaScript functionality, don't forget to include the $q service within your code.

$scope.submit = function () {
  var zipArray = this.text;
  var all = [];
  for (i = 0; i < zipArray.length; i++) {
    var got = Weather.getWeatherForecast(zipArray[i])
      .then(function (forecast) {
        return forecast;
      })
    all.push(got);
  }

  // Ensure all temperatures are retrieved before proceeding
  $q.all(all).then(function(forecasts) {

    // Assign temperatures accordingly,
    // as forecasts may not arrive in order
    $scope.temperatures = forecasts;

    $scope.zipForecast = [];

    for (i = 0; i < $scope.temperatures.length; i++) {
      var tempForecast = new weatherConstructor(zipArray[i], $scope.temperatures[i]);
      $scope.zipForecast.push(tempForecast);
    }

    // No need for toJson here, data is already an object
    $scope.DOMdata = $scope.zipForecast;
    console.log($scope.DOMdata);
  });
}


function weatherConstructor(zip,temp){
  this.zip = zip;
  this.temp = temp;
}

Answer №2

In addressing your query regarding the adherence to the "Angular Way" in this code, I'd like to emphasize the importance of simplicity in coding. Angular enables us to manipulate the DOM effectively with straightforward JavaScript, which is one of its key advantages.

It appears there's a misunderstanding about how data interacts with the DOM. In an Angular JS controller, every $scope property is automatically linked to the UI. This means changes made to the property via the DOM or programmatically in the controller will be instantly reflected in the DOM.

For your issue, I recommend keeping the end goal clear. One suggestion is to use $scope.temperatures directly instead of renaming it as DOMdata for better clarity.

<h4 ng-repeat='item in temperatures'>
    {{item.zip}} now is {{item.temp}}
</h4>

To simplify the submit logic in the controller with a target format like:

[{zip: 30224, temp: 30}, {zip: 90210, temp: 33}, {zip: 30695, temp: 28}]

The controller could be structured along these lines:

weatherController = ['$scope', Weather,
    function($scope, Weather) {
        $scope.temperatures = [];
        $scope.text = '';

        $scope.submit = function() {
            this.temperatures = []; // reset
            var zipArray = this.text.replace(/s+/g, '').split(',');
            for(var i = 0; i < zipArray.length; i++) {
                Weather.getWeatherForecast(zipArray[i]).
                then(function(forecast) {
                    $scope.temperatures.push({zip: zipArray[i], temp: forecast});
                });
            }
         };
     }
];

Lastly, consider utilizing filters to modify display values while preserving the original data:

{{item.zip}} now is {{item.temp | degrees}}.

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

Transform an array into an object with a personalized key

Here is an example array: let Given = [ ["SRM_SaaS_ES,MXASSETInterface,AddChange,EN"], ["ASSETNUM,AS_SITEID,apple,ball"], ["mesa01,SDASITE,ball,cat"], ["ASSETNUM,AS_SITEID,cat,ager"] ]; I want to organize the data in a specific way: let needed = ...

Querying JSON data in Postgres using dynamic values

Trying to query a JSON array element in Postgres 14: { "haystack": [ { "search": "findthis" }, { "search": "someothervalue" } ] } The following query works successfully: SELECT 1 FROM test WHERE ...

Tips for creating text that adjusts to different screen sizes within a div

I am trying to ensure that the height on the left side matches the height on the right, so it's important that it looks good on various devices like tablets, PCs, etc. However, when I resize my browser window, the video on the right side shrinks while ...

Using AJAX requests and $watch in AngularJS purposes

When a button is clicked, I want to dynamically generate a select menu. Using an ajax call, I retrieve JSON data from an external file upon the button click event. However, the select menu only updates with the JSON data after clicking the button twice. I ...

Is it possible to determine the success or failure of an asynchronous function when the function itself already handles errors?

The architecture of my app is currently set up with functions that are scoped to specific modules, such as "Auth" for instance: async function authenticate(email) { let authenticated = false; try { if (email) { if (!validEmail(email) ...

Can someone assist me with arranging these divs within my flexbox layout?

I'm having a tough time figuring out why the flex box aspect is making things so complicated for me. My goal is to achieve responsiveness like this - https://i.sstatic.net/MdzPO.png Despite following various flex tutorials, I haven't been succe ...

Encountering ERR_CONNECTION_RESET in AngularJS and NodeJS when using Nodemailer for POST requests

Here is the data I'm attempting to send from AngularJS to NodeJS via a POST request: $scope.doStuff = function(foo, bar) { $http({method: 'post', url: '/send', data: {foo: foo, bar: bar}}). success(function ...

My goal is to assign unique class names to each button in a list located inside a drawer, allowing them to be called individually when needed

return ( <Box sx={{ display: "flex", justifyContent: "space-between", width: "100%", height: "100%", overflow: &q ...

The Restangular back-end call is not being returned in the correct manner

I am encountering an issue where my back-end call is returning 'undefined', specifically throwing a TypeError: Cannot read property 'then' of undefined. I believe there is something incorrect with how I am making the call. Below is the ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

Strategies for managing recurring identical HTML content

Within my website, I find myself repeating similar content frequently on the same page. For example: <a href="link1"><img src="path1" alt="name1"></a> <a href="link2"><img src="path2" alt="name2"></a> <a href="link3" ...

Tips for showcasing MySQL JSON data

There is a table in my database called purchase, where I insert data in JSON format. The JSON format contains multiple sets of data, for example, "products" has 2 items. https://i.stack.imgur.com/NJ5qz.png [{"products":["Asulak Silver 7","Print Gum MAP N ...

Encountering an Issue with JSON Parsing in Laravel

Attempting to retrieve JSON data from a URL, however when using dd($data) I encounter a parse error on line 1 stating "bla bla expect string error." Initially, I suspected that my JSON object was invalid and tested with jsontest object but still encounter ...

(Original) redirect from specific url / url detection New text: "Redirection

Sorry for the long and confusing question, my apologies for wasting your time. I am still learning programming and what I really wanted to ask is "how can I retrieve a GET parameter using JavaScript?" Apologies for any inconvenience. ...

Dynamic Radio Buttons in AngularJS with Required or Optional Selections

I have developed a content management system that allows users to add various types of form fields, including radio buttons. Users can specify whether a radio button is required or not. If it is required, the user must select a radio button, otherwise a m ...

Displaying text when hovering the mouse over an element

Currently, I am working on a task that involves making a background image disappear and then revealing some text with a link in the div. Although I have managed to make the image disappear upon mouseover, I am struggling to display the text. Below is my cu ...

Using Java Script variables within Ruby code can be achieved by properly integrating the two languages through

Is there a way to incorporate a JavaScript variable into Ruby code? I attempted the following code, but it does not seem to be functioning properly. <script> var total = 100 <%@final_amount + = total%> </script> An error is being thr ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

Is it possible to apply search filters within a child component in Angular?

I have a situation where I am passing data from a parent component to a child component using *ngFor / @input. The child component is created multiple times based on the number of objects in the pciData array. pciData consists of around 700 data objects, ...

Issue with Protractor locating element even though everything appears to be in order

I'm having trouble locating this element with Protractor. It's really frustrating me. I double-checked in the dev console and the element definitely exists. Any suggestions on why it's not being found? <download path="api/backup_jobs/e ...