I am attempting to restrict the quantity of numbers shown within ng-repeat in an HTML environment

Delving into Angular development and tackling a Fibonacci sequence app. I'm seeking a way to only display the current number in the sequence using ng-repeat, as opposed to having all numbers stack up on the HTML page. Wondering if utilizing a directive or implementing "limitTo" would be the solution to dynamically show just one number at a time upon button click. Explored various solutions but none quite hit the mark for my specific issue. Any guidance would be greatly appreciated!

Here's the code snippet I've been working on:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fibonacci</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">

</head>
<body ng-app="fib" ng-controller="nextFibCtrl">

<h2 ng-repeat="result in results track by $index" | "limitTo: 1"> {{ result }} 
</h2>

<div>
<button type="button" class="reset" ng-click="clear()">RESET</button>
<button type="button" class="next" ng-click="nextNum()">NEXT FIB</button>
</div>

<script src = 
 "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.js" >
</script>
<script src="script.js"></script>
</body>
</html>

The script file I've put together:

 var app = angular.module('fib', []);

 app.controller('nextFibCtrl', function($scope,){

 $scope.results = [0, 1];

 $scope.nextNum = function(){

     $scope.currentInt = $scope.results.length -1;

     $scope.nextInt = $scope.results[$scope.currentInt] +

     $scope.results[$scope.currentInt -1];

     $scope.results.push($scope.nextInt);

  }

      $scope.clear = function(){

      $scope.results = [0, 1];

  }

  });

Answer №1

There is no need for using ng-repeat in this case. Simply initialize and reference the variable nextInt:

<h2>{{nextInt}}
</h2>

In your JavaScript code:

$scope.nextInt = 1;

Alternatively, you can also use:

<h2>{{results[results.length - 1]}}</h2>

Answer №2

Your code is encountering an issue with quotes, so make the following adjustment:

<h2 ng-repeat="result in results track by $index" | limitTo:1> {{ result }} 
</h2>

Alternatively, if you only need to display one value that is already in scope, simplify the code like this:

<h2> {{ $scope.nextInt }} </h2>

I trust this solution will be beneficial.

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

Tips for effectively invoking an MVC Controller using AJAX

I am currently working on initiating an AJAX call to a controller ActionResult within the MVC framework. While I have experience with AJAX, I am relatively new to MVC. I have set up an AJAX call in a separate .js file that is triggered by a button click ev ...

What is the best way to apply a class for styling my JavaScript code in CSS? I'm having trouble getting classList

I am having trouble adding a class to my JavaScript script in order to animate the images created in JavaScript to fall off the page. I have tried using the code element.classList.add("mystyle");, but every time I insert it, my JavaScript stops working. T ...

The variable is currently undefined because it has an array assigned to it

Upon selecting multiple checkboxes for variants, I am retrieving checked data using the following method: get selectedIdsFromViolCategoriesFormArray(): string[] { return this.violCategories .filter((cat, catIdx) => this.violCategoriesFormArr. ...

Steps to create a persistent bottom modal with scrollable content

I'm currently using Bootstrap 4.6 within my Angular application. I have implemented a modal that expands to full-screen on mobile devices, and now I want to add a fixed footer with scrolling body content. I've attempted to adjust the height of t ...

Lazy loading components in Vue enables the components on the page

While attempting to implement lazy-loading for a module within my custom Vue application, I encountered a problem. The structure of my routes is derived from a database, and one of them pertains to displaying programs for children. In this program view, I ...

Angular-leaflet-directive marker management

Is there a way to retrieve the handle of a marker so that I can set the icon when a ng-mouseover event occurs somewhere else on the page? In Leaflet, I add my markers like this: angular.extend($scope, {markers: {'id1': {lat:foo, l ...

Leveraging Redux and React to efficiently map state to props, while efficiently managing large volumes of data and efficiently

Utilizing sockets for server listening, the Redux store undergoes continuous updates with a vast amount of data. While updating the store is quick, the process of connecting the state to the component through the redux connect function seems to be slower, ...

Angular 8 carousel featuring a dynamic bootstrap 4 design with multiple images and cards displayed on a single slide

I am currently working on a dynamic carousel that should display multiple cards or images in one row. Initially, I faced an issue with the next and previous buttons not functioning properly when trying to display multiple cards in one row. After some onlin ...

I am facing some issues with the React ToDoList project

I'm a student trying to create a ToDoList using React. When I try to submit or remove a schedule, nothing happens and the lists are not updated as expected. However, if I type something in the submission box, it works! I can't seem to figure ou ...

What do you mean by "require is not defined" in Node.js

Recently delving into the world of Node.js. In my app/js file, I've got this going on: app.js var http = require('http'); http.createServer(function(request, response) { response.writeHead(200, {'Content-Type': 'text ...

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

Failed to install angularjs-server module due to an error

After attempting to install angularjs-server using the command npm install angularjs-server, I encountered an error. Similarly, when trying to install python, I faced another error. What could be causing these issues? Any suggestions for successfully ins ...

Challenges encountered when making POST requests with redux-saga

Within my application, I am making a post request using Redux Saga middleware. Below is the code snippet relevant to my post request: function* postNewMessage(newMessage) { console.log(newMessage) const {var1, var2} = newMessage; try { ...

React: "The function is not toISOString"

I am currently working on a Todo List project using Next.js. As part of the functionality, I am trying to implement a due date feature. However, when I make a post request, I encounter the following error: Unhandled Runtime Error TypeError: dueDate.toISOSt ...

How to eliminate duplicate items in an array using various criteria

I have an array arr that needs to be cleaned up by removing duplicate objects with the same e_display_id and e_type as P. In this scenario, only objects with status==='N' should be considered. Here is the input array arr: let arr = [ { e_type ...

What is a more efficient method for identifying a single, specific object without using the index approach demonstrated here?

I need to verify if the taskDetails object contains only the lastTask value and no other values. To achieve this, I am currently using the approach with index [0] as shown below: Object.keys(this.clubdetails.taskDetails)[0]==["lastTask"] However, I have ...

Angular directive using ng-if to display image

I have the following code in my showCtrl: $scope.showTeam = function(){ var count = 0; for (var k in subordinates) { if (subordinates.hasOwnProperty(k)) { ++count; } } if(count > 0){ r ...

Invoke JavaScript function upon page load

There is a link on my page that, when clicked, opens a login popup. However, I am struggling to make it work on page load. I have spent a lot of time trying to figure this out, but nothing seems to be working. <a id="onestepcheckout-login-link" href=" ...

Strategies for effectively transferring and utilizing JSON data between AngularJS and ASP.NET MVC without encountering the issue of null values

This situation reminds me of a similar issue discussed in another stack overflow thread I attempted something akin to the following question: var MyItem= { "msg": "hello word!" }; $http.post("/MyController/testPost", MyItem).success(function (data) { ...

How can I deselect the 'select-all' checkbox when any of the child checkboxes are unchecked?

Here is the code provided where clicking on the select-all checkbox will check or uncheck all child checkboxes. If any child checkbox is deselected, the 'select-all' checkbox should also be unchecked. How can this be achieved? $(document).read ...