ng-src用随机发生器显示多个图像 - Ionic 1 / Cordova

时间:2018-06-15 16:04:35

标签: angularjs cordova ionic-v1

我正在使用Ionic 1 / Cordova。我试图从一个数组中选择一个随机图像显示在页面上(这样每次用户访问时它都不同)。我得到它每次从数组中随机选择一个URL,但它会在停止之前翻阅页面上的3或4个图像。我知道ng-src的预期摘要行为,但我如何在第一个周期后阻止它或停止它?

HTML:

<md-list-item flex layout="column" layout-align="center">
    <div layout="row" layout-align="center center">
      <img class="logo" ng-src="{{resultgif(url)}}"/>
    </div>
</md-list-item>

的.js:

$scope.resultgif = function(url) {

   {
  var answers = [
"images/1500.gif",
"images/1500.gif",
"images/2000.gif",
"images/2500.gif",
"images/3000.gif",
"images/3500.gif",
"images/4000.gif",
"images/4500.gif"
]

var randomAnswer = answers[Math.floor(Math.random() * answers.length)];

};

  return randomAnswer;
  }

2 个答案:

答案 0 :(得分:0)

根据我的理解,你试图让每个周期只显示一次。我没有设置角度,但这里有一个模拟功能,可以帮助你。对于Angular,您可能必须包含$ window来访问localStorage,否则这将与vanilla js一起使用

    const answers = [
    "images/1500.gif",
    "images/1500.gif",
    "images/2000.gif",
    "images/2500.gif",
    "images/3000.gif",
    "images/3500.gif",
    "images/4000.gif",
    "images/4500.gif"
];


let randomImage = function (staticArray = [], storeName = "store") {
    let result = '';
    let _seen = localStorage.getItem(storeName);
    let _seenArr = JSON.parse(_seen);
    let allArr = [];
    staticArray.forEach(function (element, index) {
        allArr.push(index);
    });

    let rIdx = Math.floor(Math.random() * staticArray.length);


    if (_seen === null) {
        localStorage.setItem(storeName, JSON.stringify([rIdx]));
        result = staticArray[rIdx];
    } else {

        let _unseen = allArr.filter((el) => !_seen.includes(el));
        rIdx = Math.floor(Math.random() * _unseen.length);
        result = staticArray[_unseen[rIdx]];
        _seenArr.push(_unseen[rIdx]);
        localStorage.setItem(storeName, JSON.stringify(_seenArr));
        result = staticArray[_unseen[rIdx]];

        if (JSON.parse(localStorage.getItem(storeName)).length >= staticArray.length) {
            localStorage.removeItem(storeName);
        }


    }

    return result;
};


console.log(randomImage(answers));

答案 1 :(得分:0)

我通过创建一个分离函数来先选择图像,然后调用该变量。它现在每次加载1个随机图像。这里有更新的JS,它可以帮助其他人。

 var winningGif = null;

 $scope.resultgif = function() {

  var sendGif = winningGif;
  return sendGif;

  };

function getRandomGif()     {

  var answers = [
"images/1500.gif",
"images/1500.gif",
"images/2000.gif",
"images/2500.gif",
"images/3000.gif"

]

 var randomAnswer = Math.floor(Math.random() * answers.length);
 winningGif = answers[randomAnswer];

}