Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html:

    <button type="button" class="btn btn-warning" ng-click="saveInfo()">
            Save
    </button>

My goal is to implement the same functionality in the student view. The saveInfo() function passes data to a service in the app factory, which then saves the data in the database via fill_table.php. The app factory can be found in app/javascript/services.js:

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

app.factory("services", ['$http', function($http) {
var serviceBase = 'http://localhost/php/';
var obj = {};
document.title = "myApp on " + serviceBase;
obj.postData = function (user, data) {

return $http.post(serviceBase + 'fill_table.php', { "data": data, "user": {'username': user.name, 'password': user.password }).then(function (results) {
        return results.data;
    });
};

The saveInfo() function is located in app/views/subject/subject.js:

    $scope.saveInfo = function() {
    console.log("saveInfo");
    $scope.loadingInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'modalLoading.html',
      size: "l",
    });

    return getChanges( $indexedDB, $q).then( function(responsesArray) {
        var jsonData = {};
        $scope.errorInstance = undefined;
        for (var i=0; i < DB_TABLES.length; i++) {
            var table = DB_TABLES[i];
            var items = responsesArray[i]
            if (items.length > 0){
                jsonData[table] = items;
            }
        }
        console.log(JSON.stringify(jsonData));
        return services.postData($scope.selectedUser, jsonData);


    })
   }

I attempted to add the aforementioned button into app/views/student/student.html by copying the code from subject.js. However, it did not work despite ensuring all details were correct. Is there a way to specifically move that function from subject.js into Student.html?

note 1 getChanges() is another function that retrieves inserted information and passes it to saveInfo().

note 2 Currently, I can save the information inserted in the student view by pressing the save button in the subject view.

Answer №1

If my understanding is correct, you currently have two separate html files and corresponding controllers (one for student and one for subject). To facilitate data sharing and function access between these files, consider utilizing a service or factory to manage your http requests. This approach promotes reusability and ensures accessibility across all controllers.

app.factory("dataService", ['$http', function($http) {

   var addStudent = function (student) {
        return $http.post("api/Student/Add", student);
   };

   var fetchChanges = function (){
       return $http.get("api/Student/Changes");
   };

   return {
       addStudent : addStudent, 
       fetchChanges : fetchChanges 
   };
}])

You can now call upon these services within your controllers as needed.

app.controller('StudentController', ['dataService', function(dataService){
  dataService.addStudent(student).then(function successCallback(response) {
      console.log('Success');

  }, function errorCallback(response) {
      console.log('Error ' + response);

  });

  dataService.fetchChanges().then(function successCallback(response) {
      console.log('Success');

  }, function errorCallback(response) {
      console.log('Error ' + response);

  });
}]);


app.controller('SubjectController', ['dataService', function(dataService){
  dataService.addStudent(student).then(function successCallback(response){    
      }, 
      function errorCallback(response) {    
      });

  dataService.fetchChanges().then(function successCallback(response) {
      }, 
      function errorCallback(response) {
      });
  }]);

Please note that the above code snippet serves as a guideline and has not been implemented yet.

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 recommended to add the identical library to multiple iFrames?

Here's a quick question I have. So, my JSP page has 4 different iFrames and I've included JQuery UI libraries in it: <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://c ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

Using a PUT request to send parameters through the URL

My order resource implementation is structured as follows. .factory('Order', order) order.$inject = ['$resource', "ApiEndpoint"]; function order($resource, ApiEndpoint) { return $resource(ApiEndpoint.url + 'orders.json', ...

The functionality of d3.dispatch() is not performing as anticipated

Recently, I delved into the world of D3.js to explore its capabilities. One particular concept that caught my attention is d3.dispatch(), and I've been experimenting with it for about a week now. Below is a simple example: <script src="d3.min. ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

PapaParse is not properly recognizing the date format

Having trouble creating a chart using JSON data from papaparse, resulting in the following error: c3.js:2100 Failed to parse x '10-18-2018' to Date object I've tried adjusting the date format in the CSV file but haven't had any luck. I ...

Comparing a stored array in Mongo against a native JavaScript array with identical length and values results in a failed deep assert comparison

In my mongoose ORM, I have a field in mongo defined as: state: {type: [Number], required: true } When I check a sample document in the mongo console, the state appears as: state: [ 1, 1, 1 ] Everything seems to be in order so far. However, when I try t ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...

Using Angular 4 constructor value in a condition with *ngIf

Within this TypeScript snippet, there is a variable called moreinfo that is initially set to 1. In the constructor, however, the value of moreinfo is changed to 2. Subsequently, based on whether the value is 1 or 2, different div elements are displayed usi ...

Instructions on how to trigger a function after adding HTML content to the directive

When working with the viewBannerCtrl controller and using the "customTable" directive, I encountered an issue. I am unable to access the "VBC.bannerAlert()" function from the directive even though I tried appending the code to the directive. Confusingly, I ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

Validating radio button groups within an ng-repeat in Angular

Currently, I am facing a challenge in implementing radio button group validation within angular's ng-repeat structure. Here is the HTML snippet: <div ng-repeat="driver in drivers"> <input required type="radio" value="M" name="driverGender ...

Nesting promises is proving to be successful while Promise.all is currently not functioning as

My directive contains the following code structure: myApp.directive('myDirective', function(s1, s2, s3) { return { restrict:'E', link: function($scope,) { s1.then(function(data) { $scope. ...

The duplicate code is failing to display any output

Welcome to my first question here! Please excuse any rookie mistakes. I am currently working on a specialized calculator using HTML, JS (with jQuery), and CSS. This calculator is designed to handle multiple inputs and perform various calculations on a sing ...

What's the best way to align three images in a row?

I am having trouble centering three social media icons next to each other. I can't seem to figure out the proper way to do it. https://i.stack.imgur.com/Zf5p9.png <div class="maintext flipInX animated"> <div class="socials wow bounce an ...

What is the best way to extract the text inside a div element based on the input value in a

I attempted to extract the innerText of a div along with the input values within it. For instance: <div> My name is Shubham, I work for <input type="text"/> for the last 5 years.</div> My objective is to retrieve all the text ...

jQuery Autocomplete with Link Options

Can anyone help me with creating a search function for my charity's internal website? I've managed to get it partially working, but I'm struggling to make the results link to the right places. Below is the code I have so far, including test ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...