Angular新手并通过斐波那契序列应用程序。我想只重复/显示序列中的当前数字,而不是让所有数字在html页面中叠加。我应该使用指令还是限制解决方案每次单击按钮时动态显示一个数字?我寻找其他答案,但没有一个真的适合我的问题。谢谢你的帮助!
到目前为止,这是我的代码:
<!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>
我的脚本文件:
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];
}
});
答案 0 :(得分:0)
您不需要ng-repeat。只需初始化并引用nextInt
:
<h2>{{nextInt}}
</h2>
在你的剧本中:
$scope.nextInt = 1;
或者,只是:
<h2>{{results[results.length - 1]}}</h2>
答案 1 :(得分:0)
代码中的问题是引号,所以不是这样:
<h2 ng-repeat="result in results track by $index" | "limitTo: 1"> {{ result }}
</h2>
这样做:
<h2 ng-repeat="result in results track by $index" | limitTo:1> {{ result }}
</h2>
但是,考虑到您只想显示一个值,并且您已将该值绑定到范围,只需将代码更改为:
<h2> {{ $scope.nextInt }} </h2>
我希望它有所帮助