javascript - 获取错误 : shuffle(. ..) 在 angularJS 中未定义

标签 javascript angularjs undefined

当我将它放入 app.js 文件中时,它一直未定义,这并不重要。

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();
})
})();

查看

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

我已经将 Controller 放在 Controller 之外,就像我从中得到的示例所示,并尝试将其用作 $scope.shuffle,但我就是不起作用。是的,我有 body ng-app="TKC"

最佳答案

问题是您在代码中使用的 shuffle 函数“就地”运行 - 它会影响作为参数发送的数组,不返回任何内容。然而您试图立即使用它的结果。

因此,要么将 return o 添加到 shuffle 代码中,要么更改如下的 using 代码:

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

关于javascript - 获取错误 : shuffle(. ..) 在 angularJS 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25685850/

相关文章:

javascript - ExtJS 操作 propertygrid 源信息

angularjs - 仅在第一次加载数据时使用 ng-if

javascript - 创建一个函数来检查 JS 元素是否存在

javascript - 在 Angularjs 中从工厂进行调用时传递多个参数

javascript - Angular 创建数据持有者/存储库

Javascript JQuery Listview 刷新错误消息 - 未捕获的 TypeError : undefined is not a function

javascript - jquery 中的函数返回未定义

javascript - React.js 多个独立模块的最佳工作流程

javascript - 制作一个像 window.confirm 这样的函数,根据按钮单击返回 true 或 false

javascript - Fullpage.js 无限水平滚动