[英]Passing $scope variable from Controller to Service
目前正在用Ionic編寫原型應用程序,這對Ionic和angular來說還很新。 我已經編寫了一個小型的JSON API,其中包含約25個對象,已經能夠在我們稱為“庫”的頁面上顯示它們的列表,現在我嘗試使用這些列表項作為指向每個項目的單獨頁面,我們稱為“課程”。 變量$ scope.lessonId已在控制器中正確設置,但在服務中被設置為undefined。 是否有可能實現我正在嘗試的目標,或者我只是干錯了?
.controller('LibraryLessonCtrl', function($scope, $stateParams, LessonService) {
$scope.lessonId = $stateParams.libraryId;
console.log($scope.lessonId);
LessonService.getLessonId()
.then(function(response){
$scope.lesson = response;
console.log($scope.lesson);
});
})
.service ('LessonService', function($http){
return { getLessonId: function() {
return $http.get('api/postsAPI.json')
.then(function (response, lessonId) {
console.log(lessonId);
for(i=0;i<response.data.length;i++){
if(response.data[i].post_id == lessonId){
return response.data[i];
}
}
});
}
};
})
如果要使用服務內部的值,則必須將$ scope.lessonId變量傳遞給服務調用。
.controller('LibraryLessonCtrl', function($scope, $stateParams, LessonService) {
$scope.lessonId = $stateParams.libraryId;
console.log($scope.lessonId);
LessonService.getLessonId($scope.lessonId)
.then(function(response){
$scope.lesson = response;
console.log($scope.lesson);
});
}).service ('LessonService', function($http){
return { getLessonId: function(lessonId) {
return $http.get('api/postsAPI.json')
.then(function (response) {
console.log(lessonId);
for(i=0;i<response.data.length;i++){
if(response.data[i].post_id == lessonId){
return response.data[i];
}
}
});
}
};
})
您可以通過將ID傳遞給服務並將其存儲在其中來實現。 請不要將$ scope變量傳遞給服務,因為這不是一個好習慣。 您可以執行以下操作:
.service ('LessonService', function($http){
var lessionId;
return {
/*other methods*/
setLessionId: function(id) {
lessionId = id;
},
getLessionId: function(){
return lessionId;
}
};
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.