Encountering the issue: receiving an error message stating that shuffle(...) is undefined within

Whenever I try to add it into the app.js file, it keeps coming up as undefined.

app.js

(function () {
var tkcApp = angular.module('TKC', []);

var shuffle = function (o) {
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i),
    x = o[--i], o[i] = o[j], o[j] = x);
};
tkcApp.controller('ShuffleCtrl', function ($scope) {
var quotes = [
"Whatever the mind of man can conceive and believe, it can achieve. –Napoleon Hill",
"You miss 100% of the shots you don’t take. –Wayne Gretzky",
];

$scope.getQuote = function () {
  $scope.array = shuffle(quotes).slice(0, 1);
  };
$scope.getQuote();
})
})();

view

<div class="col-md-6" ng-controller="ShuffleCtrl" onload="getQuote()">
     <p ng-repeat="value in array">{{ value }}</p>
 </div>

I have tried placing it outside the controller like the example I followed, and attempted using it as $scope.shuffle, but unfortunately, it does not seem to work. And yes, I have included body ng-app="TKC"

Answer №1

The issue lies in the shuffle function being utilized in your code; it functions 'in-place', meaning it directly affects the array passed to it as an argument without returning anything. As a result, you are trying to immediately use its outcome.

To resolve this, you can either modify the shuffle function to include return o, or adjust the utilizing code as shown below:

shuffle(quotes);
$scope.array = quotes.slice(0, 1);

Answer №2

After seeking help from a colleague, I discovered the solution to my problem. The reason $scope.array was becoming empty was because the shuffle function wasn't returning a value. By adding 'return o' at the end, I was able to resolve the issue.

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

Accessing stored web pages / Browser as an interactive interface

I have a couple of questions I need help with. The first one is about how to open a saved HTML file in a browser without an internet connection. Next, I'm looking for advice on using the browser as a user interface for a desktop image viewing program ...

Maintaining the state of perspectives

I am currently working on an app that utilizes a form to filter objects from a database. Each change in the form triggers a request to the server for filtered objects, which are then displayed in another view. However, I have encountered an issue where the ...

React-Redux-Saga: Only plain objects are allowed for actions. Consider using custom middleware for handling asynchronous actions

Struggling to integrate redux-saga into my react app, I keep encountering this error: Actions must be plain objects. Use custom middleware for async actions. The error appears at: 15 | changeText = event => { > 16 | this.props.chan ...

Nodeca's js-yaml now allows appending '>-' to handle extended strings with ease

With the npm package js-yaml, I am attempting to work with a .yaml file. Although I can manipulate it successfully, I encounter an issue when trying to save a long string. Actual: abvs_adas: >- c2Rhc2Rhc2Rhc2Rhc2RwaW9qbGtkZ2hqbGtzZGhmZ2psaGFzamh ...

Creating an HTTP request inside an Export Function in a MEANJS application

Initially, I utilized the Yo MeanJs generator to kickstart my project. As a newcomer in the world of MeanJs, things are starting to look quite complex for me. Currently, my MeanJs application is supposed to retrieve data from an HTTP request but, unfortun ...

Capturing HTML form values and storing them in my JavaScript data object

I have a JS object with preset data as shown below in the variable var json. I am trying to create a simple HTML web form where I want the user inputs to be added as a new data set within my initial JS object. Here is the initial JS object data. The submi ...

Transformation of a JsonString into an array with the help of Angular.js

I have a JsonString that contains information about different car models. [{ "mileage": 12033, "name": "Ford", "model": "Focus", "engine": "3 gophers on a treadmill", "color": "green" }, { "mileage": 85000, "name": "Chevy", ...

What causes the immediate firing of the DOM callback in Angular 1.2.9?

Check out a live demo here View the source code on GitHub here Angular 1.2.9 brought in DOM callbacks with the introduction of $animate:before and $animate:after events triggered during animations. However, it seems that the $animate:after event is trigg ...

Need to know how to show a DIV for a specific time frame using Javascript?

One of the features I am looking to implement in my Django application is a display that notifies the user when one of their posts is about to start. The idea is to show a DIV element with the message: <div>“Will start soon”</div>, 15 minut ...

Utilizing ng-click and ng-switch during the submission of an Angular form

I am working on a single-page Angular app where the landing page is a sign-in form with a link to a sign-up form. The rest of the app remains hidden until the user has been authenticated. To switch between the sign-in and sign-up pages, I am using the ng ...

Whenever the download bar emerges at the bottom, the slideshow content on the page suddenly shifts upwards

Each time the download bar shows up at the bottom, the slideshow content on the Homepage suddenly moves up. It returns to its original position after I close the download bar.https://photos.app.goo.gl/F482eMfkXyfEZkdA9. My assumption is that this issue is ...

Connecting nodes to edges based on their unique ids in the d3.js graph library

I am encountering an issue with this code while trying to integrate it with a new JSON object called 'new_json'. Specifically, I need the links in this code to be created based on the nodes' IDs. Can anyone provide assistance with this? va ...

NextJS is throwing an error stating that the function file.endsWith is not recognized as a valid

After upgrading from nextJS version 9.x.x to 12.x.x, I encountered the following error. Any assistance would be greatly appreciated. TypeError: file.endsWith is not a function at eval (webpack-internal:///./node_modules/next/dist/pages/_document.js ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Issues with voice state updates in JavaScript

I am currently working on setting up a discord bot to send notifications when someone joins a voice chat. While coding in Atom, I encountered the following error: TypeError: Cannot read property 'send' of undefined at Client.client.on (C:\U ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

Creating a Nested DataTable: A Step-by-Step Guide

My data structure includes a nested dict presented as follows: var dataSet = [{"s_group": [{"range_name": null, "name": "XXXXXXXXXXXX"}], "configfile": "XXXXXXXXXXX", "src_port": ["0-65535"], ...

Leveraging the Resolve feature in AngularJS to display a template upon receiving JSON data

I am facing an issue with a URL that is being hit and the controller's model is data from an API call. Currently, the data has not been retrieved by the time the template is rendered, resulting in a blank page. I have tried using Resolve as a solutio ...

Having trouble with the Cordova button not functioning on Android 9? A beginner seeks assistance

I attempted to create a button with the id of "clickme" that links to index.html and js/buttonexample.js. Although I could see the button on both the browser and android emulator, it wasn't functioning as expected when clicked. js/buttonexample.js d ...

Vue fails to reflect changes in data when it is updated

I have a page where I can access data by calling domain.com/subpage?soundfile=something Using the fetch method, I extract the query parameter from the URL to retrieve the necessary information. The retrieval process is successful as indicated by the data ...