[英]what is the best way to write the code in ionic
我正在使用離子框架,這是我的代碼
<ion-side-menus>
<!-- Center content -->
<ion-nav-bar class="bar-positive nav-title-slide-ios7 has-tabs-top">
<ion-nav-buttons side="left">
<button class="button button-icon icon ion-navicon" ng-click="toggleDrawer()">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-side-menu-content>
<ion-view title="Home Page">
<ion-content>
hello
</ion-content>
</ion-view>
</ion-side-menu-content>
<!-- Left menu -->
**
<--below is common code in all files --->**
<drawer side="left">
<ion-nav-bar class="bar-stable nav-title-slide-ios7 has-tabs-top">
<ion-nav-buttons side="left">
<button class="button button-icon icon ion-navicon" ng-click="toggleDrawer()">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-view title="Categories">
<ion-content>
<ion-list>
<ion-item data-ng-repeat="category in categories">{{category.category_name}}</ion-item>
</ion-list>
</ion-content>
</ion-view>
</drawer>
</ion-side-menus>
以下代碼在所有文件中是通用的
<ion-list>
<ion-item data-ng-repeat="category in categories">{{category.category_name}}</ion-item>
</ion-list>
和控制器
.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
$http({
url: 'getCateogroies.php',
method: 'GET',
withCredentials: true,
})
.success((function(data) {
$scope.categories = data;
})
.error(function(data) {
alert("Login failed");
})
});
現在的問題是,它在每次頁面加載時都發送服務器請求。 我想發送一次,因為我們已經有了列表。
我們應該怎么做?
謝謝
您可以將factory
用作提供程序來訪問任何控制器中的數據。
.factory('shareData', function($http) {
var data = "undefined";
return {
getValueFromServer: function() {
//your HTTP call
data = your_response_object;
},
displayValue: function() {
return data;
}
}
});
因此,在主控制器中,您將注入工廠並調用getValueFromServer()
並獲取數據並將其存儲在工廠data
聲明的var中。 然后通過調用displayValue()
獲取值:
.controller('MainCtrl', function($scope, shareData) {
shareData.getValueFromServer();
$scope.display_t = shareData.displayValue();
})
在其余的控制器中,您只需要調用displayValue()
:
.controller('OtherCtrl', function($scope, shareData) {
$scope.display_again = shareData.displayValue();
})
我創建了具有工廠的Codepen- http ://codepen.io/keval5531/pen/ZGEZMw
您應該將$ http移出服務,然后將服務注入控制器。
.service('categoryService', ['$http', function ($http) {
function getCategories(){
return $http(/*your request here, withouth the .success, .error*/);
}
return{
getCategories: getCategories
}
}]);
然后在您的控制器中:
.controller('MainCtrl', ['$scope','categoryService',function ($scope, categoryService) {
categoryService.getCategories().then(function(success){
$scope.categories = success.data;
})
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.