Angular / Ionic - 为什么每次输入输入时我的函数都会调用?

时间:2017-02-09 23:48:01

标签: javascript angularjs json ionic-framework

我试图自学如何构建一个Angular / Ionic应用程序。我使用Backand来存储JSON,我希望每次页面重新加载时都调用一个随机的JSON值。

现在,每次输入输入时,随机调用函数都会调用。我不清楚为什么会这样。

的index.html

<label class="item-input-wrapper">
        <input type="text" placeholder="New Todo" ng-model="input.name">
</label>
<div>
  <p class="challenge-text">
       {{challenges[randomChallenge(challenges.length)].name}}
  </p>
</div>

app.js

    .controller('AppCtrl', function($scope, ViewChallenges) {
  $scope.challenges = [];
  $scope.suggested = [];
  $scope.input={};
  $scope.randomChallenge = function(length){
    return Math.floor(Math.random() * length);
}

  function getAllChallenges() {
    ViewChallenges.getChallenges()
    .then(function (result) {
      $scope.challenges = result.data.data;
    });
  }

  $scope.suggestChallenge = function(){
      ViewChallenges.suggestChallenge($scope.input)
      .then(function(result){
          $scope.input = {};
          getAllChallenges();
      })
  }



  getAllChallenges();

})

.service('ViewChallenges', function ($http, Backand) {
  var baseUrl = '/1/objects/';
  var challenges = 'challenges/';
  var suggestedChallenge = 'suggested/'

  function getUrl(x) {
    return Backand.getApiUrl() + baseUrl + x;
  };


  getChallenges = function () {
    return $http.get(getUrl(challenges));
  };

  suggestChallenge = function(suggested){
      return $http.post(getUrl(suggestedChallenge), suggested)
  }


  return {
    getChallenges: getChallenges,
    suggestChallenge: suggestChallenge
  }
});

1 个答案:

答案 0 :(得分:0)

这是因为每次更改输入时input.name都会更改。

这反过来会改变randomChallenge(challenges.length)这是一种方法。

因此,每次更改输入时,输出{{challenges[randomChallenge(challenges.length)].name}}都会受到影响。