Issue with Ionic: The view list does not reflect updated data in the controller

I am a beginner with Ionic and I'm attempting to dynamically add a list of items. I have a local JSON file and a button in my default dash.html. This button, when clicked, reads the barcode and checks if the number is available in the local JSON file. The data is then sent to the next page via app.js as shown below.

Controller.js

$scope.scanBarcode = function() {
    $cordovaBarcodeScanner.scan().then(function(imageData) {
        // alert(imageData.text);  
        if(imageData.text.length!=0){
            console.log("Barcode Format -> " + imageData.format);
            console.log("Cancelled -> " + imageData.cancelled);
            var alertPopup = $ionicPopup.alert({title: imageData.text});
            alertPopup.then(function(res) {
                $state.go('tablelist',{title: imageData.text}); 
            });
        } else {
            alert("Not captured properly. Try again");
        }

    }, 
    function(error) {
        console.log("An error happened -> " + error);
    });
};

app.js

.state('tablelist', {
  url: '/tablelist/:title',
  views: {
    'menuContent': {
      templateUrl: 'templates/tablelist.html',
      controller: 'TableCtrl'
    }
  }
})

After receiving the data in $stateParams, I can compare and add it on the next page.

.controller('TableCtrl', function($scope,$ionicPopup, $cordovaBarcodeScanner, $http, $stateParams) {
   $scope.users = [];
   $scope.barData;
   $http.get("data/menulist.json").success(function(response){ 
       $scope.barData=$stateParams;  

       for(var i=0; i<response.length; i++){
           if($scope.barData.title==response[i].barcode){
               $scope.users.push(response[i]);
           }
       }
   });   

   $scope.scanBarcode = function() {
       $cordovaBarcodeScanner.scan().then(function(imageData) {
           if(imageData.text.length!=0){
               $http.get("data/menulist.json").success(function(response){ 
                   for(var i=0; i<response.length; i++){
                       if(imageData.text==response[i].barcode){
                           $scope.users.push(response[i]);
                           $scope.apply();
                       }
                   }
               }); 
           }else{
               alert("Not captured properly. Try again");
           }
       }, 
       function(error) {
           console.log("An error happened -> " + error);
       });
   };

   $scope.removeRow = function(user){
       $scope.users.splice( $scope.users.indexOf(user), 1 );
   };
})

In the second page, there is a button to read the barcode and add it to the same list without using SQLite.

This is my tablelist.html

<ion-content>
 <button class="button button-block button-positive" ng-click="scanBarcode()">Add Product</button>
 <ion-list>
 <div class="bs-component" ng-controller="TableCtrl">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Qty</th>
                                <th>Product</th>
                                <th>Image</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                        <div ng-app>
                            <tr ng-repeat="user in users">
                                <td>
                                    <select type="number" ng-model="quantity">
                                        <option selected="selected">1</option>
                                        <option>2</option>
                                        <option>3</option>
                                    </select><br/>
                                </td>
                                <td>{{user.first_name}}</td>
                                <td><img class="td-img"  src="{{user.image}}"/></td>
                                <td>Rs: {{user.price*quantity}}
                                    <input type="button" value="Remove" class="btn btn-primary" ng-click="removeRow(user)"/>
                                </td>
                            </tr>
                        </div>
                        </tbody>
                    </table> 
                </div>

    </ion-list>
  </ion-content>

The data is successfully added to the list, but it doesn't update when I use $scope.apply() inside or outside the loop.

Could someone assist me in resolving this issue? Many have suggested that $scope.apply() should work, but it doesn't seem to be helping. Thank you in advance.

Answer №1

To calculate the total price by multiplying the quantity with the unit price :

<div>
    <tr ng-repeat="user in users">
        <td>
           <select type="number" ng-model="user.quantity">//Changed quantity to user level scope.
           <option selected="selected">1</option>
           <option>2</option>
           <option>3</option>
           </select><br/>
       </td>
       <td>{{user.first_name}}</td>
       <td><img class="td-img"  src="{{user.image}}"/></td>
       <td ng-if="user.quantity">Rs: {{user.price*user.quantity}}//checking if quantity has been selected
       <input type="button" value="Remove" class="btn btn-primary" ng-click="removeRow(user)"/>
       </td>
    </tr>
</div>

Ensure to use ng-app strictly for bootstrapping the Angular app.

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

What is causing the issue with useForm not being identified as a function?

error image Why is this error occurring when attempting to use useForm: ⨯ src\app\journal\page.tsx (18:53) @ useForm ⨯ TypeError: (0 , react_hook_form__WEBPACK_IMPORTED_MODULE_5__.useForm) is not a function at Page (./src/app/journal/pa ...

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...

Tips on accessing JSON values using a list of paths

Hello everyone, I've shared a JSON text below data = { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": ...

Distribution of data in K6 according to percentage

Is it possible to distribute data based on percentages in K6? For instance, can you demonstrate how to do this using a .csv file? ...

Protractor encountering difficulty retrieving value asynchronously

I am currently facing an issue where I need to click on an element after making a specific decision. However, during my async loops, the variable gets lost and I'm uncertain about how to retrieve the value of elt. Below is the snippet of my code: e ...

AngularJS Kinvey Image Upload with Content-Type Header

Currently, I am utilizing the AngularJS library provided by Kinvey. I have successfully managed to upload an image to Kinvey's Files. The file upload process is working fine and my image is getting uploaded without any issues. However, the problem ari ...

Display file name in Vue.js event.target.files

I am currently working on implementing an upload feature in my web application using vue 2. Here is a snippet of the code: <label class="btn btn-xs btn-primary"> <input type="file" name="attachment[]" @change="onFileChange" multiple/> ...

Using AngularJS $http to push data into JSON format

I'm trying to insert a JSON-formatted HTTP URL into the data.push() function in my code. Currently, I am populating it with random math array values. How can I properly push this JSON URL: http://maricoih.e21designs.com/services/productionhourlyscopr ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

Refresh the Angular view only when there are changes to the object's properties

I have a situation where I am fetching data every 15 seconds from my web API in my Angular application. This continuous polling is causing the Angular Material expansion panel to reset to its default position, resulting in a slow website performance and in ...

What is causing my for/in loop to return null results, while the regular for loop works perfectly fine? (VISUALS included)

My goal is to iterate through an array of objects using a for/in loop in order to log specific properties of each object to the Chrome dev console. However, I am encountering issues as I keep getting null values. As a workaround, I attempted to use a regul ...

Information regarding the PointField within the rest_framework_gis module

Currently, I am developing a web application that utilizes rest_framework_gis. One of the models in my project includes a PointField. from django.contrib.gis.db import models from django.contrib.auth import get_user_model User = get_user_model() class ...

Error encountered in Android: PatternSyntaxException due to a syntax error caused by U_ILLEGAL_ARGUMENT_ERROR

I have been utilizing json-io to convert JSON data into Java objects: DataTransferContainer dataTransferContainer = (DataTransferContainer)JsonReader.jsonToJava(json); The DataTransferContainer simply holds some GeoJson elements. This detail is irrelevan ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

I'm working on updating a field within a Firestore document using ReactJS

I am encountering an issue while attempting to update a field within a document in Firestore using ReactJS. Interestingly, others have successfully done it without any errors. app.js const app = initializeApp(firebaseConfig); const auth = getAuth(app); co ...

Display or conceal columns based on their index

<div ng-controller="checkBoxController"> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="moda ...

Navigating with Angular: How to properly redirect to a 404 error page for nested routes

I have structured my Angular application so that each feature has its own feature-routing.module.ts. These modules are then imported into the main app.module.ts. However, I am facing an issue where the application is not redirecting to /select-fund when th ...

Adding ngModel in the template causes the Angular component to load multiple times

I have been working on creating an Angular form and have successfully referenced the form in the Angular module. However, I am facing a problem where adding ngModel to an input textbox causes the Angular component to load multiple times on the page. Belo ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...

The 'RegExpExecArray | null' type is required to include a method '[Symbol.iterator]()' which returns an iterator to iterate through its values

As someone who is new to TypeScript, I have a good understanding of the basics but recently came across a typecast error that I am struggling to solve. const [full, id]: string | null = /.*media\/[^\/]+\/(.*)/.exec(item.uri) When it comes t ...