0
使用以下指令的多個實例時遇到問題。隨機地,我會在我的成功方法中得到錯誤的列表。 scope.type始終是「正確的」;這意味着它是我通過的。響應有時是來自不同呼叫的響應。
的指令:
angular.module('dincApp.directives').directive('lwSelect',
['$log', 'optionsService', '$http',
function ($log, optionsService, $http) {
return {
restrict: 'E',
replace: true,
scope:{
placeholder : '@',
type : '@'
},
link: function (scope, element, attr) {
$log.info('scope.type = ' + scope.type);
scope.options = {};
$http({method: 'GET', url: '/options/' + scope.type}).
success(function(data, status, headers, config) {
$log.info('scope.type = ' + scope.type);
$log.info('data = ' + JSON.stringify(data));
scope.options = data;
}).
error(function(data, status, headers, config) {
$log.debug('Error retrieving select options');
});
},
template:
'<select ng-options="option.key as option.value for option in options" ' +
'>' +
'<option value="">-- {{placeholder}} {{type}} --</option>' +
'</select>'
};
}]);
的HTML:
<lw-select id="stateSelect"
placeholder="State"
class="form-control"
name="state"
ng-model="profile.state"
type="State"
>
</lw-select>
任何想法?我也嘗試使用$資源,但同樣的問題發生。我不確定它與指令有關。當我在控制器中對同一個$資源進行多次調用時,也遇到過類似的行爲。
UPDATE:
我提出這個邏輯出指令到控制器和經歷相同的問題。控制器中的這些調用將在某些時間運行。其他人,我會得到返回國家的名單,反之亦然。這就像有一個競爭條件。這些調用不是單獨的實例嗎?
控制器:
optionsService.retrieve({optionType:"State"}).$promise.then(
function success(response) {
$log.debug('Options response for stateOptions:' + JSON.stringify(response));
$scope.stateOptions = response;
},
function failure() {
$log.error('Error retrieving select options');
});
optionsService.retrieve({optionType:"Country"}).$promise.then(
function success(response) {
$log.debug('Options response for countryOptions:' + JSON.stringify(response));
$scope.countryOptions = response;
},
function failure() {
$log.error('Error retrieving select options');
});
....
資源:
angular.module('dincApp.services').factory('optionsService',
['$resource',
function ($resource) {
return $resource('/options/:optionType', {}, {
retrieve: { method: 'GET', isArray: true }
});
}]);
這是一個有點很難說你的意思到底是什麼,但嘗試設置一個變量到你的$ http返回(即承諾),然後在'然後'設置數據。 var val = $ http(....); val.then(function(data){$ scope.options = data;});這種事 – Scott 2014-09-24 00:08:15
基本上,我在同一頁面上有幾個指令的實例。我以爲我正在使用隔離範圍。 scope.type在我的日誌中看起來正確。他們隨機地讓對方返回數據。 – 2014-09-24 01:19:22
而不是在鏈接中做它在控制器中 – Seminda 2014-09-24 02:09:38