在Angular 1.5中使用组件生成一个随机数

Generating a random number using components in Angular 1.5

本文关键字:随机数 一个 组件 Angular      更新时间:2023-09-26

我试图在ng-click事件上生成随机数。目前它正在生成一个随机数,但是只有一次,然后它依赖于浏览器刷新,然后生成另一个数字。

我相信这可能与我声明变量sample的方式有关。

angular.module('FOO', [])
  .component('foo', {
    controller: fooController,
    controllerAs: 'foo',
    template: template()
});
function template() {
  return [
  '<button ng-repeat="move in foo.moves" ng-click="foo.gameplay(move)" >',
    '{{ move }}',
  '</button>',
 ].join('')
}
function fooController() {
  var self = this;
  self.gameplay = gameplay;
  self.moves = ['var1', 'var2', 'var3']
  var sample = Math.floor(Math.random() * (self.moves.length));
  function gameplay(clicker) {
    console.log(sample);
  }
}

试试这个

function fooController() {
  var self = this;
  self.gameplay = gameplay;
  self.moves = ['var1', 'var2', 'var3']
  var sample = Math.floor(Math.random() * (self.moves.length));
  function gameplay(clicker) {
    sample = Math.floor(Math.random() * (self.moves.length));
    console.log(sample);
  }
}

为什么不使用

function gameplay(clicker) {
  var sample = Math.floor(Math.random() * (self.moves.length));
  console.log(sample);
}