Controller function not being triggered by ng-click directive

I'm currently working on an Ionic app and trying to use ng-click to call a function from my controller. Below is the function I want to call:

function startSpin() {
    if ($scope.wheelSpinning == false) {
        spinWheel.animation.spins = 9;
        spinWheel.startAnimation();
        $scope.wheelSpinning = true;
    }
}

function resetWheel() {
    spinWheel.stopAnimation(false);
    spinWheel.rotationAngle = 0;
    spinWheel.draw();

    $scope.wheelSpinning = false;
    $scope.$apply();
}

The aim here is to create something similar to a wheel of fortune game using the winWheel.js library sourced from . In my view, I want to call the startSpin() and resetWheel() functions from buttons. Here's the corresponding code:

<canvas id="canvas" width="300px" height="315px" style="margin: 25px">
    Canvas not supported
</canvas>
<button onClick="spinWheel.startSpin()">Spin the Wheel</button>
<a href="javascript:void(0);" onClick="spinwheel.resetWheel();">Reset</a>

However, when clicking the spin button, it returns an error in the console:

Uncaught ReferenceError: spinWheel is not defined

Furthermore, when using the ng-click directive, no output is generated as if the button is disabled. I seem to be missing something here and would appreciate any help or guidance. If more information is needed, feel free to ask. Thank you for your assistance.

Note that this is just a portion of the code in my controller. The complete code can be found below:

.controller('PlayCtrl', ["$scope", "$ionicPopup", function($scope, $ionicPopup) {
 var spinWheel = new Winwheel({
'numSegments' : 6,
'outerRadius' : 138,
'lineWidth'   : 2,
'segments'    :         
[
  {'fillStyle' : '#eae56f', 'text' : 'Segment 1'},
  {'fillStyle' : '#89f26e', 'text' : 'Segment 2'},
  {'fillStyle' : '#7de6ef', 'text' : 'Segment 3'},
  {'fillStyle' : '#e7706f', 'text' : 'Segment 4'},
  {'fillStyle' : '#0D56A6', 'text' : 'Segment 5'},
  {'fillStyle' : '#29c932', 'text' : 'Segment 6'}
],
// Animation specifications
{
  'type'       : 'spinToStop',
  'duration'   : 5,
  'spins'      : 10,
}

});

$scope.wheelSpinning = false;

//Click handler for spin button.
function startSpin()
{
if ($scope.wheelSpinning == false)
{
  spinWheel.animation.spins = 9;
  spinWheel.startAnimation();
  $scope.wheelSpinning = true;
}
}

// Function for the reset button.
function resetWheel()
{
spinWheel.stopAnimation(false);
spinWheel.rotationAngle = 0;
spinWheel.draw();

$scope.wheelSpinning = false;
$scope.$apply();
}

// Callback function once spin animation finishes
alertPrize = function()
{
var winningSegment = spinWheel.getIndicatedSegment();

$ionicPopup.alert({
  title: 'Success',
  content: "You have won " + winningSegment.text + "!"
});

}

$scope.spinWheel = startSpin();

}]);

Answer №1

By implementing ng-click, your application may become unresponsive if the spinWheel.startSpin() method is not accessible within the scope.

There are two potential solutions to this issue:

  1. Add the spinWheel object to the scope and include the startSpin method within it.

Controller Example:

$scope.spinWheel = {
    var startSpin = function() {
      //Code goes here
    }
    var stopSpin = function() {
      //Code goes here
    }
}

  1. Refer to the controller as 'spin wheel' in your HTML code.

<div ng-controller = "PlayCtrl as spinWheel">
   <button onClick="spinWheel.startSpin()">Spin the Wheel</button>
   <a href="javascript:void(0);" onClick="spinwheel.resetWheel();">Reset</a>
</div>

Answer №2

To implement the desired functionality, replace the line $scope.spinWheel = startSpin(); with the following code:

$scope.spinWheel ={
                       startSpin:startSpin,
                       resetWheel:resetWheel
                };

Instead of using onClick="spinWheel.startSpin()", use ng-click="spinWheel.startSpin"

ng-click="spinWheel.startSpin"

Similarly, instead of onClick="spinwheel.resetWheel();", use ng-click="spinWheel.resetWheel"

ng-click="spinWheel.resetWheel"

By making these changes, the functionality will work as expected.

Answer №3

After conducting thorough research, I was able to successfully resolve the issue. I made some changes in my controller's code:

function startSpin()
{
    //...
}

and

function resetWheel()
{
    //
}

I updated it to:

$scope.startSpin = function()
{
    //
}

and

$scope.resetWheel = function()
{
    //
}

As a result, I could access both functions in my view:

<button ng-click="startSpin()">Spin the Wheel</button>

and for the reset option:

<a href="javascript:void(0);" ng-click="resetWheel()">Reset</a>

Answer №4

Your spinWheel class is not in scope in the code you shared above. To fix this, try the following:

 $scope.spinWheel= new Winwheel({
'numSegments' : 6,      // Specify number of segments.
'outerRadius' : 138,    // Set outer radius so wheel fits inside the background.
'lineWidth'   : 2,
'segments'    :         // Define segments including colour and text.
[
  {'fillStyle' : '#eae56f', 'text' : 'Segment 1'},
  {'fillStyle' : '#89f26e', 'text' : 'Segment 2'},
  {'fillStyle' : '#7de6ef', 'text' : 'Segment 3'},
  {'fillStyle' : '#e7706f', 'text' : 'Segment 4'},
  {'fillStyle' : '#0D56A6', 'text' : 'Segment 5'},
  {'fillStyle' : '#29c932', 'text' : 'Segment 6'}
],
'animation'    :        // Specify the animation to use.
{
  'type'       : 'spinToStop',
  'duration'   : 5,     // Duration in seconds.
  'spins'      : 10,    // Number of complete spins.
  // 'callbackFinished'  : 'alertPrize()'    // Alert to show prize won
}

});

Now you can use its function on your view just like you were doing before.

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

The Dynamic Data Duo: JSON and Python

Currently, I am in the process of creating a web interface for Arduino using Python, with JSON being utilized for automatic updates and display. However, an intriguing issue has arisen. Within the code snippet below, a command is sent to a python function ...

Ways to set the minimum width of a div depending on its contents

As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...

Beginning the setup process in an Ionic app interface

After creating an Ionic app blank, I went ahead and created a templates folder with a file named login.html in it. My goal is to have the login.html page show up when the app starts. I attempted to achieve this using the following code: app.js angular. ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Authorization header is swapped out by Internet Explorer 11

Why is Internet Explorer replacing the HTTP header? Authorization : Bearer <server-provided-token> with Authorization : Negotiate <some token> when sending an AJAX request? The Issue In some cases, Internet Explorer replaces the header Au ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

'this' in Arrow functions does not have a reference to the calling context

Something seems off about the context in this code. I've left comments to describe my issue below: const cat = { //arrow function meow: () => { console.log(this); }, makeMeow(){ // Why does 'this' refer ...

accomplishing validation in Angular forms while avoiding the use of the HTML form tag

I'm looking to implement Angular Form Validation without the use of an HTML form. I attempted the following code, but unfortunately, the button remains enabled. <ng-form name="login"> <div class="input-group"> <span class="input ...

What is the best way to include multiple parameters in config.route.js with Angular?

I am facing an issue while trying to pass multiple parameters in my config.route.js file. I have successfully passed one parameter, but encountering difficulties in passing two parameters. The second parameter is optional. Can anyone provide insight on h ...

Track when a user modifies a <select> dropdown list generated using the Jquery method ".html()"

Is it possible to detect a change in the value of a select list when that select list has been added using either the .html(htmlString) or .append(content[,content]) jQuery function? HTML CODE: <ul class="htmlClass"> <!-- Populated via JS --& ...

Content must be concealed following the third paragraph

Dealing with an API that generates content in p tags, which can become excessively long. Considered hiding the content after 400 characters, but it poses a risk of cutting through HTML tags. Instead, looking to hide the excess content after 3 paragraphs a ...

Can you suggest a more efficient method for retrieving data from a string?

Imagine having an array of strings with various information, and you need to extract specific details from them. Is there a simpler method to achieve this task? Consider the following array: let infoArr = [ "1 Ben Howard 12/16/1988 apple", "2 James S ...

When using WordPress with Angular in HTML5 mode, if you try to refresh the page, it may result

As I navigate through my Angular app using routing, everything works smoothly when I click links from within the app. However, when I attempt to directly access a specific app URL, the server responds with a 404 error. Below is the configuration I am usin ...

Executing a console.log statement within an array nested inside a function of an object

Today in school, I learned about objects and how a function inside an object is actually called a method. In my method, I have an array and I'm trying to change a global variable to display a different location in the console.log. However, all I keep ...

What could be causing the issue of req.body being undefined within the destination function of Multer's diskStorage?

I'm currently utilizing Multer for managing file uploads within my Express.js application. However, I've encountered an issue when attempting to access the req.body values in the destination function of Multer's diskStorage option – it con ...

Unlocking the Secrets: Retrieving Message Embeds Using Discord.js' Message ID

I've been working on creating an advanced suggestion command and here is the progress I've made with the code: if (command === 'accept') { try { const suggestionchan = bot.channels.cache.get('840493081659834403'); const a ...

A guide on shading specific faces based on their normal vectors' alignment with the camera's view

https://i.sstatic.net/FG4hp.png I'm currently working on a shader that requires darkening the faces with normals perpendicular to the camera (dot product is 0). How can I calculate this dot product and make sure it works correctly? uniform float tim ...

Error message: "PHP encounters an issue with jQuery due to absence of 'Access-Control-Allow-Origin' header"

I am currently attempting to make an external API call in PHP using AJAX and jQuery, but I keep encountering the error message saying "No 'Access-Control-Allow-Origin' header is present". The API does not support JSONP. Is there any workaround t ...