问题描述
我去了一个带有指令的小角度应用程序。 为了从服务器端检索数据,我使用ngRoute。 检索数据后,我将结果绑定到scope属性,并使用ng-repeat解析结果,如下所示:
<div class="col-xs-12" ng-repeat="clsRow in classificatorData">
<span>{{clsRow.code}}</span>
</div>
此功能从资源中检索数据
var getClassificatorDataScope = function (criteria, predicate) {
references.initialize('classificators');
references
.getRefereces(null, $scope.classificatorType, criteria, predicate == null ? "NONE" : predicate, $scope.limitLevel, null)
.$promise.then(function (result) {
$scope.classificatorData = result.Data;
});
};
一切正常。 但是如果我尝试像这样实现传递结果数据容器(dataScope)
var getClassificatorDataScope = function (criteria, predicate, dataScope) {
references.initialize('classificators');
references
.getRefereces(null, $scope.classificatorType, criteria, predicate == null ? "NONE" : predicate, $scope.limitLevel, null)
.$promise.then(function (result) {
dataScope = result.Data;
});
};
像这样在控制器中使用它
getClassificatorDataScope("CODE", null, $scope.classificatorData);
我什么都没有。 请帮助我了解这种行为。
1楼
这里有两个问题。
dataScope = result.Data;
第一个是这个。
这并不像您期望的那样。
它不会替换$scope.classificatorData
。
它所做的只是将getClassificatorDataScope
的本地dataScope
变量替换为result.Data
(是的,它不是“通过引用传递”)。
其次,您使用的诺言不正确。
您返回的承诺是倾听,而不是将范围传递给谁知道哪里。
您的数据层通常不应该知道$scope
或UI。
将promise返回给控制器,并让其监听来自它的数据。
// In your function
var getClassificatorDataScope = function(criteria, predicate) {
references.initialize('classificators');
return references
.getRefereces(null, $scope.classificatorType, criteria, predicate == null ? "NONE" : predicate, $scope.limitLevel, null)
.$promise
};
// In your controller
getClassificatorDataScope("CODE", null).then(function(result){
$scope.classificatorData = result.Data;
});
2楼
问题可能出在您的reference.getRefereces方法中。 它应该返回一个Promise,然后用适当的结果来解决它(我看到您尝试从result中访问“ Data”属性。)。 像这样的东西:
reference.getReferences = function() {
var deferred = $q.defer();
someAsyncOperations(function callback(){
deferred.resolve({Data: result}) // make sure you have the "Data" attr
})
return deferred.promise;
// or if someAyncOperations already return a promise
// return someAsyncOperations.then(function(result) {
// return {Data: result};
// });
}
3楼
似乎在第二个示例中,您尝试将从服务器检索到的数据分配给dataScope
但是由于AJAX数据加载是异步的,因此$promise
的解析要晚于使用ng-repeat
绘制的模板。
没有足够的代码来编写整个示例-应该如何实现。
但是基本上,您应该从服务中返回$promise
,并在控制器中更改$ scope变量
promise.then(function() {
//do stuff with $scope variables
})