我想教自己如何構建一個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
}
});
由於角度摘要循環的工作方式,在視圖中具有返回隨機值的功能真的很糟糕。在控制器中分配一次變量 – charlietfl