Unable to invoke controller function from view

I am trying to invoke the controller function from the view. Below is my current view setup:

   <body>
   <div ng-app="appTable">
      <div ng-controller="Allocation">
         <button ng-click="add()"> Add </button> 
         <button ng-click="remove()">remove</button>
         <table>
            <th>
            <td>Date</td>
            <td>Project</td>
            <td>Release</td>
            <td>Feature</td>
            <td>Module name</td>
            <td>Hours spent</td>
            <td>Comment</td>
            </th>
            <tr ng-repeat="data in dataList">
               <td><input type="checkbox" ng-model="data.isDelete"/></td>
               <td>
                  <input type="text"
                     datepicker
                     ng-model="data.date" />                 
               </td>
               <td><input type="text" ng-model="data.dept"/></td>
               <td>
                  <select ng-model="data.release" ng-options="x for x in range">
                  </select>
               </td>
               <td>
                  <select ng-model="data.feature" ng-options="x for x in feature">
                  </select>
               </td>
               <td>
                  <input type = "text" ng-model = "data.modulename">
               </td>
               <td>
                  <select ng-model="data.hours" ng-options="x for x in hours">
                  </select>
               </td>
               <td>
                  <input type = "text" ng-model = "data.comment">
               </td>
            </tr>
         </table>
         <button ng-click="Submit()">Submit</button>
         <table>
            <tr ng-repeat="data in displayList">
               <div ng-controller="Allocation as vm">
                  <div>{{vm.postdata(data.date)}}</div>
               </div>
               <p>Output Message : {{msg}}</p>
               <p>StatusCode: {{statusval}}</p>
               <p>Status: {{statustext}} </p>
               <p>Response Headers: {{headers}} </p>
               <td>
                  <p>{{data.date}}</p>
               </td>
               <td>
                  <p>{{data.dept}}</p>
               </td>
               <td>
                  <p>{{data.release}}</p>
               </td>
               <td>
                  <p>{{data.feature}} </p>
               </td>
               <td>
                  <p>{{data.modulename}}</p>
               </td>
               <td>
                  <p>{{data.hours}}</p>
               </td>
               <td>
                  <p>{{data.comment}}</p>
               </td>
            </tr>
         </table>
      </div>
   </div>
</body>

The script utilized is as follows.

<script>
    var app = angular.module("appTable", []);

    app.controller("Allocation", function($scope) {
        $scope.hours = ["1", "2", "3"];
        $scope.range = ["1", "2", "3"];
        $scope.feature = ["UT", "FSDS", "Coding/Devlopment", "QA"];

        $scope.dataList = [{
            date: '17/07/2016',
            dept: 'OneCell',
            release: '1',
            feature: "UT",
            modulename: "Redundancy",
            hours: "1",
            comment: "Add extra information"
        }];

        $scope.add = function() {
            var data = {};
            var size = $scope.dataList.length;
            if (!size) {
                $scope.dataList = [{
                    date: '17/07/2016',
                    dept: 'OneCell',
                    release: '1',
                    feature: "UT",
                    modulename: "Redundancy",
                    hours: "1",
                    comment: "Add extra information"
                }];
            } else {
                size = size - 1;
                data.date = $scope.dataList[size].date;
                data.dept = $scope.dataList[size].dept;
                data.release = $scope.dataList[size].release;
                data.feature = $scope.dataList[size].feature;
                data.modulename = $scope.dataList[size].modulename;
                data.hours = $scope.dataList[size].hours;
                data.comment = $scope.dataList[size].comment;
                $scope.dataList.push(data);
            }

        };

        $scope.Submit = function() {
            $scope.test = "Submit is pressed...";
            $scope.displayList = [];
            angular.forEach($scope.dataList, function(v) {
                if (!v.isDelete) {
                    $scope.displayList.push(v);
                }
            });
            $scope.dataList.splice(0);


        };
        $scope.remove = function() {
            var newDataList = [];
            angular.forEach($scope.dataList, function(v) {
                if (!v.isDelete) {
                    newDataList.push(v);
                }
            });
            $scope.dataList = newDataList;
        };

        $scope.postdata = function(date) {

            var data = {
                date: date,
            };
            $http.post('/add_status/', data).then(function(response) {
                if (response.data)
                    $scope.msg = "Post Data Submitted Successfully!";
            }, function(response) {
                $scope.msg = "Service not Exists";
                $scope.statusval = response.status;
                $scope.statustext = response.statusText;
                $scope.headers = response.headers();
            });
        };


    });


    app.directive("datepicker", function() {

        function link(scope, element, attrs, controller) {
            // CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
            element.datepicker({
                onSelect: function(dt) {
                    scope.$apply(function() {
                        // UPDATE THE VIEW VALUE WITH THE SELECTED DATE.
                        controller.$setViewValue(dt);

                    });
                },
                dateFormat: "dd/mm/yy" // SET THE FORMAT.
            });
        }

        return {
            require: 'ngModel',
            link: link
        };
    });
</script>

I have included the postdata function within the controller and it utilizes the msg variable internally. However, there seems to be an issue with displaying the value of this variable in the view. Any assistance or guidance on resolving this would be greatly appreciated since I am relatively new to AngularJS.

Answer №1

If you want to improve your code, consider the following suggestions:

  1. Remove the line ng-controller="Allocation as vm", since you have already defined the controller above and are not using the this syntax in it.
  2. Once you have removed the as vm part, you no longer need to prefix your calls with vm..
  3. Don't forget to inject $http into your controller to make API calls.

To see a demo of these changes in action, check out this fiddle. I have logged dummy text in the console for each submission click.

For an example of how to make a single call on submit, take a look at this Fiddle.

Answer №2

A proper way to display the value in the function is by returning a value or adding a scope variable to be shown in the controller's div. Currently, nothing is being displayed.

<div ng-controller="Allocation as vm">
                  <div>{{vm.postdata(data.date)}}</div>
               <p>Output Message : {{msg}}</p>
               <p>StatusCode: {{statusval}}</p>
               <p>Status: {{statustext}} </p>
               <p>Response Headers: {{headers}} </p>
</div>

It is not recommended to run procedural functions directly like this. It is better to bind it to an event like ng-click.

Also, ensure that only td or th elements are created as child elements within a tr.

The correct HTML table structure should look like this:

<table>
 <tr>
   <th>Month</th>
   <th>Savings</th>
 </tr>
 <tr>
   <td>January</td>
   <td>$100</td>
 </tr>
</table>

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

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

What is preventing ShowViaLink() from functioning properly in Firefox and Internet Explorer?

I am facing an issue with my webpage where the navigation does not work on Firefox or IE, but it works perfectly fine on Chrome. I suspect that the problem lies in this code, as when I made changes to it, the navigation stopped working on Firefox & IE: ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

Obtaining a 16-bit integer from the response of an LWIP server

On the server side, I have implemented a loop that takes a 16-bit integer ranging from 0 to 639 and splits it into two 8-bit characters to populate a buffer of 1280 Bytes. The buffer is then sent via TCP-IP to the client. .c unsigned int data2[1000]; ch ...

Exploring the JsonArray Response entity

Trying to decode my fetch response: fetch('restservices/users/', fetchOptions) .then(function (response) { if (response.ok) { console.log('1'); console.log(response) const responseSjon = response.json ...

Placing emphasis on an object that appears following a period of waiting

I'm currently working on enhancing the accessibility of a slider that will be featured on my website. The goal is to create an effect where, after clicking (or pressing enter) on the first slide, the focus shifts to the second slide element, allowing ...

Fade out and slide close a div using jQuery

I am creating a new website and incorporating jQuery for animation and simplified JavaScript implementation. My goal is to have a button that, when clicked, will close a div with a fading out and slide up effect. Can this be achieved? Thank you. ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

A JavaScript function that is only triggered half of the time

After browsing through various forums like StackOverflow, I couldn't find a solution that perfectly fits my issue. I may be new to programming, but I've managed to create several projects already. Currently, I am working on integrating them into ...

React's useContext not reflecting changes when state is updated

After successfully converting my class component to a functional one with the use of useContext, I am facing some challenges in accessing and retrieving the status changes. Specifically, I have a component named input.js located at src/components/input.js. ...

The issue of VueRouter malfunctioning in history mode within Wordpress

I have integrated Vue into my Wordpress theme, but I am facing an issue with the router when setting mode: 'history'. The site goes blank and even after trying to configure the .htaccess file, nothing seems to work. My project is located in the V ...

Step-by-step guide on replicating the style of a div class

I'm attempting to create a comments counter div that changes color based on the number of comments. If there are 0 comments, the div should be red, and if there are more than 0 comments, the div should be blue. However, I am encountering an issue with ...

Automatically play the elements within a div using jQuery

I have various sections within different divs that I want to display without the need for manual clicking on tabs. While I've been able to toggle the visibility of these sections by clicking, I would prefer them to display automatically in a loop usin ...

Can you explain how I can configure the express module for routing?

directories /config -routes.js /public /views -index.pug /home -home.pug -app.js app.js const express = require('express'), app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.se ...

I've been attempting to send a file to an API but keep running into the error: "Objects are not valid as a React child, please use an array instead."

I've attempted to upload a file to my API, but I encounter the following error message: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. Here is the code snippet for submitting the data: ...

Passing a div's ID value using AngularJS AJAX to store it in a PHP variable

I have a collection of div elements, each with a unique id. My goal is to trigger a JavaScript function when a specific div is clicked. This function should send the id value of the clicked div to PHP, assign it to a PHP variable, and then receive a respon ...

Is it possible to configure Lambda NodeJS 12.x flags (like --experimental-modules) when using AWS SAM local start-api?

When setting up my nodejs server, I chose to use ES6 module syntax: package.json "type": "module" So far, running my server locally as a nodejs process has been successful. For example: "scripts": { "dev": "npm outdated ; nodemon --experimental-modul ...

Exploring JSON Data in Node-Red

Currently utilizing Node-Red for the purpose of counting individuals by implementing a flow that can successfully detect faces using visual recognition node. Presented below is the output from the Visual Recognition node taken directly from the Debug windo ...

Ways to loop through elements in a sliced array?

JS : var addData = function(data) { var portion = 40; $scope.items = []; console.log(data.length + "hi"); for (var i = 0; i < data.length; i += portion) { console.log("inside for loop"); $scope.items.push(data.slice(i, ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...