What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of points available can be allocated across 4 different categories.

Custom Directive

angular.module('components', []).
  directive('addSkills', function() {
    return {
      restrict: "A",
      scope: {
        max: '=',
        min: '=',
        pointValue: '='
      },
      template: '<div>' +
                  '<span>{{scoreValue}}</span>' +
                  '<button ng-click="addPoints()" ng-disabled="pointValue >= max">+</button>' +
                  '<button ng-click="minusPoints()" ng-disabled="pointValue <= min">-</button>' +
                  '</div>',
      link: function(scope, element, attrs) {
        scope.addPoints = function() {
          scope.scoreValue += 1;
          scope.$parent.pointsAvailable -= 1;
        };
        scope.minusPoints = function() {
          scope.scoreValue -= 1;
          scope.$parent.pointsAvailable += 1;
        };
      }
    }
  });

Controller

angular.module('myControllers', []).
controller('skills', function($rootScope, $scope, $http, $location, $q) {
  $scope.pointsAvailable = 10; // Initially set here, but will be dynamic
  $scope.skills = {};
  $scope.skills.strength = {
    points: 0,
    description: '...',
    // additional properties
  };
  $scope.skills.speed = {
    points: 0,
    description: '...',
    // additional properties
  };
  $scope.skills.intelligence = {
    points: 0,
    description: '...',
    // additional properties
  };
});

HTML

// more html code before
<div class="skills">
  <h4>{{pointsAvailable}}</h4>
  <div class="skillRating">
    <label>Strength: </label>
    <div data-add-skills data-point-value="skills.strength.points" data-max="pointsAvailable" data-min="0"></div>
  </div>
  <div class="skillRating">
    <label>Speed: </label>
    <div data-add-skills data-point-value="skills.speed.points" data-max="pointsAvailable" data-min="0"></div>
  </div>
  <div class="skillRating">
    <label>Intelligence: </label>
    <div data-add-skills data-point-value="skill.intelligence.points" data-max="pointsAvailable" data-min="0"></div>
  </div>
</div>

In this setup, as points are added to each skill, the variable $scope.pointsAvailable decreases accordingly. For example, if you allocate 3 strength points, only 7 remain to distribute among other skills.

I attempted modifying "pointsAvailable" upon clicking the increment buttons, but encountered a roadblock where allocating all points to one skill capped at 5 points, rendering the increment buttons unusable. Each increase in points decreased "pointsAvailable", preventing the allocation of all 10 points to a single skill.

Answer №1

If you're looking for a simple way to display skills without using a directive, I've put together a basic example: http://jsfiddle.net/ADukg/4768/

This demo utilizes the ng-repeat functionality to showcase the shared attributes among different skills.

Check out the code snippet below:

<div ng-controller="MyCtrl">
  Points available: {{pointsAvailable}}
   <div ng-repeat="skill in skills">
    <div class="skillRating">
        <label>{{skill.name}}</label>
        <div>
            <span>{{skill.score}}</span>
            <button ng-click="addPoints(skill)" ng-disabled="skill.score >= skill.max || pointsAvailable <= 0">+</button>
            <button ng-click="minusPoints(skill)" ng-disabled="skill.score <= skill.min">-</button>
        </div>
      </div>
   </div>
</div>

For reference, here's the controller logic:

function MyCtrl($scope) {
    $scope.pointsAvailable = 10;

    $scope.skills = [
        { name: 'strength', score: 0, max: 8, min: 0 },
        { name: 'speed', score: 0, max: 10, min: 0 },
        { name: 'intelligence', score: 0, max: 5, min: 0 }
    ];

    $scope.addPoints = function(skill) {
        skill.score += 1;
        $scope.pointsAvailable -= 1;
    };

    $scope.minusPoints = function(skill) {
        skill.score -= 1;
        $scope.pointsAvailable += 1;
    };
}

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

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

Unlock the power of json data traversal to derive cumulative outcomes

Our goal is to populate a table by parsing a JSON object with predefined header items. (excerpt from an answer to a previous query) var stories = {}; for (var i=0; i<QueryResults.Results.length; i++) { var result = QueryResults.Results[i], ...

Customize HTML styles using Angular Material

I've noticed that my index.html file has a lot of style elements when using Angular Material, and I'm not sure why. Here's an example in the header element where different classes are used for Angular Material components. Is this setup corr ...

When making an Ajax request to a controller, rather than simply returning JSON data, it redirects you to a

Utilizing jQuery and MVC 5, I have implemented a modal form in my project. Upon clicking 'ok' on the modal box, the javascript function should trigger an ajax call to the "Companies/Createa" controller. The code successfully executes and update ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Create a consistent number based on quantity

Looking to generate a sequence of numbers equal to the count in PHP or JavaScript for my application. For example, if my total count is 7: <?php $total = 7; I would like to generate seven 1's like this: $split_one = [1,1,1,1,1,1,1]; If my count ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Display an image in an Angular application using a secure URL

I am trying to return an image using a blob request in Angular and display it in the HTML. I have implemented the following code: <img [src]="ImageUrl"/> This is the TypeScript code I am using: private src$ = new BehaviorSubject(this.Url); data ...

Update the var value based on the specific image being switched using jQuery

I have implemented a jQuery function that successfully swaps images when clicked. However, I am now looking to enhance this functionality by passing a parameter using $.get depending on the image being displayed. Here is the scenario: I have multiple comm ...

Configure the input to accept integer values

This page that I have developed is designed for entering Latitude and Longitude values. <div class="container "> <form class="entry"> <div class="aligncenter"> <h5 style="color:MediumTurquoise; font ...

Utilizing React's createRef() for Enzyme testing

I am currently using the new React.createRef() api in one of my components. I am trying to figure out how to test if document.activeElement is equal to the current ref component. Here is the component code: export class Automatic extends Component { c ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

Automatically close Bootstrap 4 modal popups

I am using Bootstrap 4 and trying to make my modal automatically close after 3 seconds. I attempted a solution but it seems to not be functioning correctly. The modal itself works fine, but the auto-closing feature is not working as expected. Below is the ...

During development, getStaticPaths and getStaticProps successfully function, however, the prop during build time becomes undefined

I am currently working on developing an eCommerce platform utilizing Next.js. One of the challenges I encountered was in the product page where dynamic routes are used. Specifically, I implemented getStaticProps to fetch the product and getStaticPaths to g ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

Tips for updating the default value of an HTML <select> tag using a customized <select> option

I'm struggling to update the value of my <select><option value=""></option></select> based on a custom select option I created. Customizing select options using JS and jQuery is necessary since they can't be easi ...

Guide on utilizing JSON data sent through Express res.render in a public JavaScript file

Thank you in advance for your assistance. I have a question that has been on my mind and it seems quite straightforward. When making an app.get request, I am fetching data from an external API using Express, and then sending both the JSON data and a Jade ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

What steps can I take to resolve a Bootstrap form validation issue where the email field is causing the label to shift down?

I am currently troubleshooting an issue in a website using Visual Studio, which is built with VB.NET, ASP.NET, HTML, CSS, and Bootstrap. The problem lies in the input validation under the email addresses. While one validation is working fine, the validatio ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...