AngularJS - Display Modified Content on Page

Check out the JS Fiddle: https://jsfiddle.net/q6rqk90s/ (Works on server and local computer, but not on JsFiddle.com)

AngularJS CODE


angular.module('RealParkClicker', [])
    .controller('ParkController', ParkController)
    .directive('messageBox', messageBox);

function ParkController($scope){
  $scope.title = 'Real Park Clicker - Manage your park from anywhere!'; 
  $scope.promo = 'Start clicking to buy thrilling rides!';
  
  $scope.parkOwner = "Enter name";
  $scope.parkName = "Enter park name";
  $scope.parkOpen = true;

  $scope.ownedRides = 0;
  $scope.totalGuests = 0;
  $scope.allTheGuests = 0;

// Rides
$scope.rides = [
{
name: "Merry Go Round",
price: 10,
gpm: 1,
img: 'img/merrygoaround.jpg',
owned: 0
},
{
name: "Swinging Ship",
price: 20,
gpm: 5,
img: 'img/swingingship.jpg',
owned: 0
},
{
name: "Free Fall Tower",
price: 40,
gpm: 10,
img: 'img/freefall.jpg',
owned: 0
},
{
name: "Log Flume",
price: 50,
gpm: 15,
img: 'img/logflume.jpg',
owned: 0
}
];

$scope.changeOwner = changeOwner;
$scope.changeParkName = changeParkName;
$scope.addGuest = addGuest;
$scope.buyRide = buyRide;
$scope.sellRide = sellRide;

$scope.$watch('totalGuests', function(newValue, oldValue){
        $scope.totalGuests = newValue;
});

function changeOwner(){
    $scope.parkOwner = $scope.newOwner;
    $scope.newOwner = '';
}

function changeParkName(){
    $scope.parkName = $scope.newParkName;
    $scope.newParkName = '';
}

function addGuest(){
    $scope.totalGuests++;
    $scope.allTheGuests++;
}

function buyRide(index){
    if($scope.totalGuests === $scope.rides[index].price || $scope.totalGuests > $scope.rides[index].price ) {
    $scope.rides[index].owned +=1;
    $scope.totalGuests -= $scope.rides[index].price;
    $scope.ownedRides +=1;

    var rideGPM = $scope.rides[index].gpm;

    setInterval(function(){ generateGuests(rideGPM); }, 3000);
}
}

function sellRide(index){
if($scope.rides[index].owned > 0) {
    $scope.rides[index].owned -=1;
    $scope.totalGuests += $scope.rides[index].price;
    $scope.ownedRides -=1;
}
}

// Generate Guests Function
function generateGuests(number){
    var rideGPM = number;
    $scope.totalGuests += rideGPM;
}

}

ParkController.$inject = ['$scope'];

function messageBox(){
    return {
        restrict: 'E',
        template: '<div><input ng-model="newMessage"/><button ng-click="sendMessage()">Send</button></div>',
        controller: 'ChatController'
    };
}

Index.HTML Code


<!doctype html>
<html>
<head>
    <link href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css" rel="stylesheet" />
    <link href='https://fonts.googleapis.com/css?family=Roboto:500,300,700,400' rel='stylesheet' type='text/css'>
    <link href="css/main.css" rel="stylesheet" />
    <title>Real Park Clicker</title>
    <script src="js/angular.min.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-app="RealParkClicker">
<div ng-controller="ParkController">
<div class="header">
<div class="container">

    <h1>Real Park Clicker</h1>

    <h2>Park Name: {{parkName}}</h2><br/>

<input ng-model="newParkName"/>
<button ng-click="changeParkName()">Set Park Name</button>


<h3>Park owner: {{parkOwner}}</h3>

<input ng-model="newOwner"/>
<button ng-click="changeOwner()">Set owner</button>

</div>
</div>
<div class="main" ng-controller="ParkController">
<div class="container">
    
    <h2>{{promo}} <button ng-click ="addGuest()">Add 1 Guest</button> {{totalGuests}}</h2>

    <div ng-repeat="ride in rides track by $index" class="col-md-6">
                <div class="thumbnail">
        <img ng-src="{{ride.img}}">
        <p class="title">{{ride.name}}</p>
        <p class="price">{{ride.price}} Guests</p>
        <p class="gpm">This ride generates {{ride.gpm}} guests per second.</p>
        <p class="owned"> You own {{ride.owned}} of this ride</p>
        <div class="store">
          <p class="buy" ng-click="buyRide($index)">Buy</p>
          <p class="sell" ng-click="sellRide($index)">Sell</p>

      </div>
    </div>
</div>
</div>

<center>
<h3>Park Stats</h3>
<ul>
    <li>Total owned Rides: {{ownedRides}}</li>
    <li>User Generated Guests In Total: {{allTheGuests}}</li>
</ul>
</center>

<div class="footer">
<div class="container">
<h2>Available for iPhone and Android.</h2>
<img src="https://s3.amazonaws.com/codecademy-content/projects/shutterbugg/app-store.png" width="120px" />
<img src="https://s3.amazonaws.com/codecademy-content/projects/shutterbugg/google-play.png" width="110px" />
</div>
</div>
</div>
</body>
</html>

Building a clicker game where users can manage a theme park. Guests increase by clicking "Add 1 Guest", and users can purchase amusement rides using the total number of guests. Each ride generates guests per second. The challenge is updating the guest count automatically without needing user interaction. Tried implementing various methods such as $watch and ng-onchange with no success. Appreciate any guidance!

Answer №1

The problem you're facing is due to Angular not recognizing the need to update the displayed value. This occurs because your generateGuest function is invoked with setInterval, causing it to run outside of the angular context.

A simple solution would be to replace setInterval with the angular $interval function (or $timeout if your angular version doesn't support $interval). This change should resolve the issue.

To better understand why this is happening, consider looking into $scope.$apply and $scope.$digest.

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

Find the JavaScript code that selects the previous value chosen

When working with a select in React, I am facing an issue where the console.log is returning the last value selected instead of the current one. For instance, if I select 4 followed by 3 and then 5, the code will display 1 (default value), then 4, and fin ...

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

The issue with AngularJS ng-model not functioning properly with dynamically generated input fields

I have set up a dynamic templateUrl for form fields and I am attempting to use ng-model within ng-repeat. The parent directives and form field directive are functioning correctly and being generated, but when I try to apply ng-model it does not seem to wor ...

Pass along property to subsequent middlewares in Express

Within my express app, I have implemented auth middleware that identifies the current user based on the session ID. I am seeking a way to "persist" the user object and make it accessible to subsequent middlewares. I attempted attaching the user object to t ...

Simple trick to automatically hide the div in AngularJS when clicking outside of it

I want to hide my div for notifications when clicked outside of it. Here is the plunker code link containing the HTML code: <div ng-hide="notification" ng-click="notifications($event);"><i class="fa fa-bell" aria-hidden="true ...

Unable to understand the reason behind the malfunctioning of angular binding in the codepen script

I am attempting to utilize angular in my codepen project, as it seems to be supported. However, I am encountering an issue where I am unable to bind to my controller's $scope object for some reason. I have experimented with different versions of angul ...

What is the best method for implementing page transitions between components in NextJS?

My goal is to create a form that smoothly slides to the right, similar to the one seen on DigitalOcean's website when you click "Sign up using email" here: . While the transition itself is relatively simple, I noticed that DigitalOcean uses 2 separat ...

How can CSS and JavaScript be used to strategically position two upright images next to each other within a dynamically resizing container?

Looking for a way to display two portrait images side by side within a flexible container with 100% width? The challenge I'm facing is accommodating varying widths of the images while ensuring they are the same height. <div class="container"> ...

The issue occurs when the AngularJS model is not updated upon selecting a date with bootstrap-datepicker

Currently, I am incorporating AngularJS with a bootstrap-datepicker plugin found here: This specific Datepicker for Bootstrap is version 1.6.4 and can be found at https://github.com/eternicode/bootstrap-datepicker. Credits go to Stefan Petre (2012) and An ...

Troubleshooting issue with default button in asp.net using javascript

Despite my best efforts, I couldn't figure out how to make a button default until I came across a helpful tip from someone here who shared some javascript code that checks for the enter key in a textbox and triggers the button. I attempted placing my ...

Tips for retaining previous data while loading in React hooks

Just started using react hooks and built my initial component. Everything is functioning properly except for a flickering issue while the data is loading. Here is my component (a basic list of articles with previous/next pagination): function InfoFeed ({ l ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...

Issues encountered when integrating Nextjs with React Native and Expo

Attempting to set up an Expo project with Next.js, I executed the expo init command expo init . in my directory. The initial setup appeared to be successful. Following the steps outlined at , specifically under the section on adding Next.js to Expo project ...

Monitoring the inclusion of a new item within the database

I am utilizing a Firebase Realtime Database where users have the ability to perform the following actions: add an item to the database update an item in the database Currently, I have a function that monitors a specific location within the database. ...

Preventing users from inputting the same number more than once

Here are a series of text input fields pertaining to a single question: <input type="text" name="{{ $answer->id }}" value="" style="width:20px; text-align:center" maxlength="1" oninput="this.value=this.value.replace(/[^0-5]/g,'');" /> & ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

What is the best way to determine the position of an internal SVG element in relation to the viewport of an outer SVG element?

Consider an SVG element with various components: <div style="margin-left:50px; width: 100%; min-height: 400px;"> <svg> <g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%"> <svg x="20" y ="50" style ...

Error in Vue Google Maps: Marker not defined

I'm currently working on integrating a single location map using Google Maps in Vue 2 with Vue-google-maps-2. Despite using code that has successfully worked for other parts of the application where multiple markers are plotted from an array, I am enc ...

Modify the behavior of the Android back button when a Popup is displayed in Ionic

I'm attempting to accomplish the following: Scenario 1 User presses the back button. A popup appears asking if the user wants to exit * User presses the back button. The app exits * and Scenario 2 User presses the back button. A popup ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...