我正在angularJS中的一個小應用中工作,該應用使用對API服務的調用來獲取,顯示和操作數據。
剛開始的時候一切都很流暢和簡單,但是當我不得不在不同控制器下的應用程序的不同部分顯示相同的數據時,我開始將所有API調用移動到工廠以共享該數據和控制,如果沒有需要,可以提出另一個請求。
但是由此產生了一個不同的問題:請求已發出,數據放入適當的$ scope中,但是沒有任何更改會反映在視圖中,直到我手動單擊某處以與視圖進行交互爲止。
我一直在嘗試使用$ scope。$ apply和$ scope。$ watch;我設法使它工作,但現在我發現自己在很多地方使用延遲,這對我來說似乎非常不自然。
我會告訴你例如用戶配置文件的代碼,看看我在說什麼。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Demo</title>
</head>
<body ng-app="app" ng-controller="DashboardCtrl">
<div ng-init="getOwnProfile()">
<h1>My account</h1>
<form class="inline-form" role="form">
<input type="hidden" value="2" name="id"/>
<div class="form-group has-error">
<ul class="input-grp-2">
<li><input name="first_name" type="text" ng-model="profile.first_name" placeholder="First name" /></li>
<li><input name="last_name" type="text" ng-model="profile.last_name" placeholder="Last name" /></li>
</ul>
</div>
<input name="phone" type="text" ng-model="profile.phone" placeholder="Phone number"/>
<textarea name="information" rows="7">{{ profile.information }}</textarea>
<a href="#" class="button btn-add-photo"><span class="glyphicon glyphicon-camera"></span> Add Photo</a>
<input style="display: none" type="file" name="image" class="upload-photo" id="input_upload" accept="image/*"/>
</form>
<a href="" target="_self" class="button btn-green" ng-click="updateProfile(profile)">Submit Changes</a>
</div>
<script src="/js/app.js"></script>
<script src="/js/controllers/dashboard.js"></script>
<script src="/js/api.js"></script>
</body>
</html>
我的儀表盤控制器使用:
$scope.profile = null;
$scope.getOwnProfile = function() {
$scope.$watch('profile', function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.profile = API.getOwnProfile();
});
}, 100);
})
};
和API服務設置配置文件爲:
var APIService = {};
var ownProfile;
APIService.resetRenterProfile = function() {
ownProfile = undefined;
};
APIService.getOwnProfile = function() {
if (typeof ownProfile === 'undefined') {
retrieveOwnProfile();
}
return ownProfile;
};
retrieveOwnProfile = function() {
return Restangular.one('profile', null).get() // GET: /profiles
.then(function (profile) {
ownProfile = profile;
});
};
return APIService;
正如我所說的,工作的,但我有兩個問題。
1)在每個控制器中提取數據並將其放入正確範圍的正確範圍內,但是這些$範圍數據都不會顯示在視圖中,直到用戶對視圖產生某些影響,例如單擊在一個下拉菜單中,在一個標籤等
2)我必須指定一個延遲以毫秒爲單位,如果由於任何原因,對後端的API調用需要更多的時間比該延遲,美元範圍數據是直到用戶手動與視圖交互時才顯示。
我很喜歡它的工作方式,我的印象是我以錯誤的方式去做,所以我想如果有人能指出我如何避免或改善這類問題。
非常感謝。