Adjust the scope variable upon submission and refresh the display in AngularJS

Currently, I am working on my first web app using angularjs and facing an issue where the page does not update with new values once the user submits text or numbers in an input box.

For this project, I am utilizing Java8, MongoDB, angularJS, and twitter bootstrap.

HTML:

<td>
  <input type="text" class="form-control" placeholder="enter bugnumber" data-ng-model="auditdata.newbugnumber"> 

  <h4>Bug Numbers</h4>

  <a href="{{bugLink(a)}}" data-ng-repeat="a in parseBug(auditdata.bugnumber) track by $index">{{a}}</a>

</td>

<td>
  <button type="submit" data-ng-click="add(auditdata)" class="btn btn-danger" >Save</button>
</td>

In the HTML code above, I capture user input in ng-model=auditadata.newbugnumber. However, on the server side, it still updates the bugnumber field. The newbugnumber serves as a temporary variable to transmit the new data to the server, preventing two-way binding in AngularJS.

I've attempted to use $apply(), $watch, and digest in the JavaScript below but haven't been able to update the value in the view. Reloading the page is currently the only way the data reflects changes in the view, which is not ideal:

app.controller('listCtrl', function ($scope, $http,$route) {

$scope.isCollapsed = true; 

$http.get('/api/v1/result').success(function (data) {
    $scope.audit = data;   

}).error(function (data, status) {
    console.log('Error ' + data);
})

$scope.add= function(bugInfo) {
     $http.post('/api/v1/result/updateBug', bugInfo).success(function (data) {
             bugInfo.newbugnumber='';
             console.log('audit data updated');
         }).error(function (data, status) {
             console.log('Error ' + data);
         }
   };   
});

Update function on the server-side:

public void updateAuditData(String body) {

        Result updateAudit = new Gson().fromJson(body, Result.class);
        audit.update(
                new BasicDBObject("_id", new ObjectId(updateAudit.getId())),
                new BasicDBObject("$push", new BasicDBObject().append("bugnumber",
                        updateAudit.getNewbugnumber())));
    }

The structure of the "bugnumber" field in the collection:

> db.audit.find({"_id" : ObjectId("5696e2cee4b05e970b5a0a68")})
{
        "bugnumber" : [
                "789000",
                "1212"
        ]
}

Answer №1

After considering your feedback, here is a suggested approach:

It is recommended to centralize all your $http requests in a service or factory for better organization and ease of testing

app.factory('AuditService', function($http) {
  var get = function() {
    return $http.get("/api/...") // returns a promise
  };

  var add = function() {
    return $http.post("/api/...") // returns a promise
  };

  return {
    get: get,
    add: add
  }
});

Then in your controller:

// Make sure to import AuditService into the controller
app.controller('listCtrl', function ($scope, $http,$route, AuditService) { 

// Additional code here


// If the insertion is successful, update the $scope with the new collection using then()
$scope.add = function(bugInfo) {
  AuditService.add().then(
    function(){ // success callback
      AuditService.get().then(
        function(data){ // success
          $scope.audit = data; 
        },
        function(error){ // error
          console.log('error reading data ' + error)
        })
    },
    function(error){ // error callback
      console.log('error inserting data ' + error)
    })  
});

This modular approach can be extended to handle all CRUD operations efficiently

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

Guide on implementing Two Sensor Manager for Accelerometer and Magnetometer within a single Java class

In my application, I have two separate programs for the Accelerometer and Magnetometer sensors, both utilizing the Sensor Manager. The issue arises when I attempt to combine these two programs into one to gather data from both sensors. It seems that the ...

What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

concealing your password within a Java class file as part of a testing scenario

I am currently developing a Selenium test case for our company's Jenkins server, where all employees have access to view the Java files I create. public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get(" ...

Guide to display half of an image and allow for full image viewing upon mouse hover

After creating my bootstrap 4 website, I encountered an issue with the code below where only half of the image is displayed initially due to a conflict in the code. It also fails to work properly when moving the mouse after shifting the whole image from ri ...

Passing a list variable to JavaScript from Django: A step-by-step guide

Currently, I am facing an issue while attempting to generate a chart using Chartjs and Django. The problem arises when transferring data from views.py to the JavaScript code. Here is a snippet of my code in views.py: def home(request): labels = [&quo ...

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

Configuring various options on numerous dropdowns using AngularJS

I am looking for a solution to customize dropdowns created through ng-repeat in AngularJS. The number of dropdowns displayed is determined by the data fetched from the database. I want to be able to set an initial option value for each dropdown based on th ...

Adjust the template within a directive to dynamically include an additional directive

Challenge Create a custom directive that dynamically adds the ng-bind attribute, allowing for the use of ng-bind, ng-bind-html, or ng-bind-html-unsafe without needing to manually add it to the template definition throughout. Illustrative Example http://j ...

Guide to implementing nested conditions to reveal a hidden block with AngularJS

I need help setting up conditions to display a hidden div. I want the hidden block to appear only after entering a value in the 'name' textbox and clicking on the search link. Currently, the hidden div appears even if the search link is clicked b ...

Play template files are displaying a validation error in the Scala IDE that needs to be addressed

After installing the latest release of Scala IDE (Build id: 4.1.0-vfinal-20150525-1102-Typesafe) to work on my Playframework project (version 2.4), I encountered a problem with validation errors in the play template files (.scala.html). Although the projec ...

Tips for accessing the content of a div tag with Protractor

Currently, I am working on developing a test that needs to click on a link within a div. However, there is an issue with my XPath locator due to some recent changes made by the developer in the UI. Using Xpath may not be a viable solution as the UI is subj ...

How can I integrate Apple remote support into a website with the use of Javascript?

One thing that I find interesting is the ability to use the Apple remote with Front Row, as well as other apps on Mac that support it. I'm curious about whether Web Apps could also be made compatible through Javascript. I have a concept for a TV-like ...

Recommendations for Configuring VPS for Angular2 and .Net Application

My team and I are currently in the process of developing an application that combines Angular2 for the front-end and Web API ASP.NET for the back-end. We are currently at the stage of configuring a VPS for this application but unfortunately, we lack the ...

WebSocket functionality in Node.js utilizing the ws module from npm

I am currently working on developing a chat application. The first step involves the user sending their username, and if the name does not already exist, they are logged in. The user can then send a message to another user. However, an issue arises where a ...

Button for Toggling Audio Play and Pause

Is it possible to create an SVG image that changes color slightly when hovered over, and when clicked toggles to another SVG image that can be switched back to the original by clicking again with the same hover effect? Additionally, when clicked, it should ...

Retrieve a JSON object from a JSON array using a specific key

I am facing a situation where I have a json array containing multiple json objects. Let's take the example of a course object with the following structure: {"name": "Math", "unit": "3"} The json array looks something like this: [{"name": "Math", "u ...

Challenges arise with the height settings of ui-grid

Currently, I am facing an issue with using height: auto on an angularJS ui-grid. The problem arises from an inline style that specifies a fixed height on the div to which the ui-grid attribute is added. Additionally, the function getViewPortStyle() dynamic ...

Is it possible to enable tab navigation for a button located within a div when the div is in focus?

I have a component set up like this: (Check out the Code Sandbox example here: https://codesandbox.io/s/boring-platform-1ry6b2?file=/src/App.js) https://i.sstatic.net/ZuxdL.png The section highlighted in green is a div. Here is the code snippet: import { ...

Combining meanings within a geometric interface

When setting up my routes, I like to include an additional field in the configuration. This is how I do it: app.config([ '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => { $routeProvider ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...