Incorporating new topics into the existing roster

I am currently developing a leaving cert points calculator as a Single Page Application (SPA) website. Users are required to tick checkboxes for the subjects they have taken, enter their grade, and specify the level at which they took the subject.

Although I have successfully implemented the interface and calculation functions, I am facing challenges in adding subjects to a new array named 'takenSubjects' based on whether the checkbox is checked or not.

Here is a glimpse of the current interface:

The goal is to input the grade as a string (which will convert to the corresponding points), along with the level specified using radio buttons to calculate the total points. The 'taken' checkbox serves as a boolean to determine whether the subject should be added to the array for calculating the overall points.

While my experience with AngularJS is limited, I am utilizing a factory to manage my functions. Below is the JavaScript code I have written so far:


factory.getSubjects = function () {
    return subjects;
};

/*  
factory.getTakenSubjects = function () {
    return 
};

factory.getGrade = function () {
    scope.subjects.push({
        grade: $scope.newGrade.grade;
    });
}

factory.total = function (subjects, levels,grades) {
    var total=0;
    for(var i=0;i<subjects.length;i++){
        total+=gradeToPoints(subjects[i],levels[i],grades[i]);
    }
    return total;
};

factory.gradeToPoints = function(subject,level,grade){
    var results = 0;
    if(level==="Higher"){
        results = higherGradeToPoints(grade);
        if (subject === "Mathematics" && results>0){
            results += 25;
        }
    }else if(level==="Lower"){
        results = lowerGradeToPoints(grade);
    }else{
        if(subject === "Mathematics" || subject === "Irish"){
            results = foundGradeToPoints(grade);
        }
    }
    return results;
};      

factory.foundationGradeToPoints = function (grade) {
    switch (grade){
        case "A1":
            return 20;  
        case "A2":
            return 15;
        case "B1":
            return 10;
        case "B2":
            return 5;
    }   
    return 0;   
};

factory.lowerGradeToPoints = function (grade) {
    switch (grade){
        case "A1":
            return 60;

        case "A2":
            return 50;

        case "B1":
            return 45;      

        case "B2":
            return 40;      

        case "B3":
            return 35;

        case "C1":
            return 30;

        case "C2":
            return 25;

        case "C3":
            return 20;

        case "D1":
            return 15;

        case "D2":
            return 10;

        case "D3":
            return 5;   
    }
    return 0;
};

factory.higherGradeToPoints = function (grade) {
    switch (grade){
        case "A1":
            return 100;

        case "A2":
            return 90;

        case "B1":
            return 85;

        case "B2":
            return 80;

        case "B3":
            return 75;

        case "C1":
            return 70;

        case "C2":
            return 65;

        case "C3":
            return 60;

        case "D1":
            return 55;

        case "D2":
            return 50;

        case "D3":
            return 45;
    }
    return 0;
};
*/
return factory;
})

.controller('SimpleController', function($scope, simpleFactory) {
        $scope.subjects = simpleFactory.getSubjects();
});

Answer №1

To efficiently create a list of subjects in the html view, consider using ng-repeat for iteration. Additionally, utilize ng-model to set checkboxes on initialization and update them as needed.

<div ng-controller="myCtrl1">
  <div ng-repeat="subject in subjects track by $index">
    <input type="checkbox" ng-model="subject.taken[$index] ng-change="setTaken(subject, $index, value)""/>
    <span>{{subject.name}}</span>
  </div>
</div>

In the controller, define a method like setTaken to pass the taken status of each subject to the factory. Make sure to implement a getter function to initialize the ng-model value using the getTaken method.

$scope.setTaken= function(subject,$index, value){
   simpleFactory.setTaken(subject,value);
}

Lastly, within the factory, create a method to store data in a backend or other storage medium for retrieval by the getter function.

Answer №2

It might be beneficial to consider adjusting the architecture of your application. This could involve modifying the factory and enhancing the controller. I can provide some guidance, but not the complete code for the entire application. That part will require some exploration on your end.

Here are a few steps you could take: 1) Start by adding var takenSubjects = []; at the beginning of your factory. This array will store the subjects that have been taken.

2) Implement a function in your factory that allows you to add an object with subject details to the array. The function should resemble this:

    factory.addTakenSubject = function(subject) {
        takenSubjects.push(subject);
    };

    //The objects being added should follow this structure - don't worry about specifics for now.
  {
    subject: 'Accounting',
    taken: true,
    level: "ordinary",
    gradeReceived: "A"
  }

3) Now, it's time to connect models to all fields in your HTML. Here's how you can attach a model to a checkbox field as an example:

To detect if a checkbox is checked, assign a model to it within the view (HTML). Remember, the factory cannot directly interact with the view, so the controller must retrieve the checkbox state (true if checked, false if unchecked), then pass it to SimpleFactory.addTakenSubject(subject)

For instance, your HTML may include:

   <input type="checkbox" ng-model="subject.taken"> //should be in scope of SimpleController

Similarly, for the level (higher, ordinary, foundation), the HTML would look like: ... ...

Remember - ng-repeat will likely be used to list items in your HTML.

------You can handle the rest - essentially adding HTML for the remaining input fields. You're likely familiar with this!

- 4) Next, you'll need to create a function in your controller that captures the value of taken (either true or false) and assigns it to a variable in your factory.

For example:

   .controller('SimpleController', function($scope, simpleFactory) {
        $scope.subject={subject:"", taken:false, level:"", gradeReceived:""};//taken defaults to false
        $scope.add = function() {
        simpleFactory.addTakenSubject($scope.subject);//$scope.subject will no
        });
      });

Ensure that your ng-model matches the corresponding object key in the controller.

And that's a good starting point. You don't have to strictly adhere to these instructions, but they should offer some assistance!

A word of caution: validate the syntax when defining a factory. Here's a sample factory definition:

     var app = angular.module('myApp', []);
     app.factory('myFactory', [function(){
        var takenSubjects = [];
        return{
           addTakenSubject: function() {
               takenSubjects.push(subject);
           }
         }
   }]);
  //this demonstrates one function; additional key-value pairs can be included in the return object.
  //**remember - factories return objects**

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

"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to ...

Converting a TypeScript class to a plain JavaScript object using class-transformer

I have a few instances of TypeScript classes in my Angular app that I need to save to Firebase. However, Firebase does not support custom classes, so I stumbled upon this library: https://github.com/typestack/class-transformer which seems to be a good fit ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

Utilize JavaScript within a PHP foreach loop for submission

Modifying my query I have a form with submit functionality without refreshing the page, however this form is embedded within a foreach loop Where should I place the JavaScript code? Inside the foreach loop or outside? If it's placed outside, how ca ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

Enhancing Stock Information with AJAX and Java

I'm currently developing a stock trading application that relies on Yahoo Finance to retrieve stock prices. My goal is to have the prices automatically update every 5 seconds without needing to refresh the page. I understand that this can be achieved ...

Error: The identifier has already been declared and cannot be re-declared

I am attempting to create a modal-cookie feature that will display a modal on page load if a cookie named "name" does not exist. However, I encountered an error: Uncaught SyntaxError: Identifier 'addCookie' has already been declared. This erro ...

The lookAt method in THREE.js is not functioning properly when called after the rendering process

The code snippet below seems to be causing some issues. It requires jquery and three.js to function properly. The problematic lines are as follows: // change the view so looking at the top of the airplane views[1].camera.position.set( 0,5,0 ); views[1].ca ...

What is the best way to upload an image through PHP using $_POST after using JavaScript to resize it?

I am currently working on developing a webpage that allows users to upload images from their iPhone, Android, and desktop devices. The goal is to save these pictures as thumbnails in the ./userupload directory and store the link to them in a MySQL database ...

Creating dynamic canvas elements with images using HTML and JavaScript

Currently, I am working on a unique project involving a canvas filled with dynamic moving balls. This project is an extension or inspired by the codepen project located at: https://codepen.io/zetyler/pen/LergVR. The basic concept of this project remains t ...

Is it recommended to create model classes in React components?

Within the realms of React, the Flux architecture is utilized. According to https://reactjs.org/docs/thinking-in-react.html, React operates with two distinct models - namely, the state and props. There are recommendations provided for model management in ...

Accessing attributes declared in the constructor from within class methods is not possible

I am encountering an issue with my HomeController and its index method. I have declared a variable called `this.data` in the constructor, but when I try to access it within the index method, I get the following error message: TypeError: Cannot read proper ...

Creating Functions with HTML, CSS, and Javascript

I have been working on a website that is designed to convert numbers for you. Most of the code is complete, but I have encountered an error that I am currently unable to resolve. When I try to run the code, I see content on the page but when I click the ...

Collapsed Bootstrap navigation bar on mobile devices

Hello everyone, I am currently using the latest version of Bootstrap for my website. However, I have encountered an issue where the navigation collapses on mobile view. Could anyone provide assistance? Website: Below is a snippet of my HTML code: <he ...

Error encountered: Attempting to access the property 'statusCode' on an object that is undefined within the Request._callback

When trying to create a new Ionic app, I encountered the following error: C:\Users\orcilia49\AppData\Roaming\npm\node_modules\ionic\lib\cli.js:474 process.stdout.write('Unable to fetch', err ...

What is the method to access 'let' variables in the console of a developer tool?

When you open the Chrome devtool and enter the code snippet below: // The iife is irrelevant let r = (() => { return 2; })(); and then evaluate r, the output will be: r 2 Surprisingly, both window.r and globalThis.r return undefined. Although let is ...

Develop a dynamic animation using gradient and opacity properties

I'm still getting the hang of HTML, JavaScript, and CSS but I recently made some changes to someone else's code to animate a gradient. The original code used background: rgb, but I switched it to background: rgba. It seems to be working fine, but ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

What are some tips to ensure that my JavaScript submissions always execute correctly?

I'm facing an issue with uploading a canvas draw image using JavaScript in a .php file. The SQL data submission to the database always works, but the upload of the canvas draw image doesn't consistently function. This problem occurs specifically ...

Is there a way to remove the highlight from a non-active block?

Hey friends, I need some help with my code. Currently, when I click on a table it gets highlighted, and if I click on another table, the previous one remains highlighted along with the new one I clicked on. How can I modify the code so that when I click on ...