AngularJS和JS Math.max.apply()不能一起工作

AngularJS and JS Math.max.apply() not working together

本文关键字:不能 一起 工作 apply JS Math max AngularJS      更新时间:2023-09-26

我正在阅读一本关于学习AngularJS的书中的一个代码示例,但有些东西并不像书中所示的那样起作用。在Chrome和Firefox中打开html页面时,角度表达式没有问题,直到最后一个。有什么办法让最后的胡子显示正确的东西吗??

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.Math = window.Math;
    $scope.myArr = [];
    $scope.removedArr = [];
  });
<!doctype html>
<html ng-app="myApp">
  <head>
    <title>AngularJS Expressions</title>
    <style>
      a{color: blue; text-decoration: underline; cursor: pointer}
    </style>
  </head>
  <body>
    <div ng-controller="myController">
      <h1>Expressions</h1>
      Array:<br>
        {{myArr}}<hr>
      Elements removed from array:<br>
        {{removedArr}}<hr> 
      <a ng-click="myArr.push(Math.floor(Math.random()*100 + 1))">
        Click to append a value to the array</a><hr> 
      <a ng-click="removedArr.push(myArr.shift())">
        Click to remove the first value from the array</a><hr>
      Size of Array:<br>
        {{myArr.length}}<hr>
      Max number removed from the array:<br>
        {{Math.max.apply(Math, removedArr)}}<hr>   
	</div>  
    <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
    <script src="js/expressions_javascript.js"></script>
  </body>
</html>

感谢@dnc253给出它不起作用的简单原因,并感谢@charlietfl提供最佳解决方案。这是我做这件事的新手方法。

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.Math = window.Math;
    $scope.myArr = [];
    $scope.removedArr = [];
    $scope.maxNumm;
    
    $scope.maxNummm = function()
    {
    	$scope.maxNumm = Math.max.apply(Math, $scope.removedArr);
    	console.log("maxNumm: " + $scope.maxNumm);
    };
    
  });
<!doctype html>
<html ng-app="myApp">
  <head>
    <title>AngularJS Expressions</title>
    <style>
      a{color: blue; text-decoration: underline; cursor: pointer}
    </style>
  </head>
  <body>
    <div ng-controller="myController">
      <h1>Expressions</h1>
      Array:<br>
        {{myArr}}<hr>
      Elements removed from array:<br>
        {{removedArr}}<hr> 
      <a ng-click="myArr.push(Math.floor(Math.random()*100 + 1))">
        Click to append a value to the array</a><hr> 
      <a ng-click="removedArr.push(myArr.shift()); maxNummm();">
        Click to remove the first value from the array</a><hr>
      Size of Array:<br>
        {{myArr.length}}<hr>
      Max number removed from the array:<br>
      <!-- For security reasons, you can no longer invoke the
      	apply function in an angular expression -->
        <!-- {{Math.max.apply(Math, removedArr)}} -->
        {{maxNumm}}
        <hr> 
	</div>  
    <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
    <script src="js/expressions_javascript.js"></script>
  </body>
</html>

enter code here