2017-02-09 91 views
0

我想教自己如何构建一个Angular/Ionic应用程序。我使用Backand来存储JSON,并且我希望每次重新加载页面时都会调用一个随机的JSON值。Angular/Ionic - 为什么我每次输入输入时都会调用函数?

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

的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 
    } 
}); 
+0

由于角度摘要循环的工作方式,在视图中具有返回随机值的功能真的很糟糕。在控制器中分配一次变量 – charlietfl

回答

0

这是因为input.name改变每次你改变输入。

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

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

+0

您能解释为什么每次输入input时input.name都会改变吗?我将我的项目建立在本教程的基础上:https://devdactic.com/ionic-backend-database/,它并没有真正从概念上解释发生了什么。 – user3183717

相关问题