我有服务从服务器获取数据并将其发送到控制器:
服务:
publicApp.angularModule.factory('resultService', function ($http) {
return {
getResult: function() {
return $http.get("/Result/GetResult")
.success(function(result) {
return result.data;
}).error(function(result) {
console.log("error" + result);
});
},
};
});
控制器:
publicApp.angularModule.controller('PublicResultCtrl', function ($scope, $location, resultService) {
resultService.getResult().then(function (resultResponse) {
$scope.data = resultResponse.data;
$scope.graph = [];
_.forEach($scope.data.TreningExerciseScores, function(item) {
$scope.graph.push(addDataToGraph(item.Item2, item.Item1));
});
});
var addDataToGraph = function (num, text) {
return {
y: num,
legendText: text,
};
};
});
我有指令应该从控制器获取数据 . 我像这样调用指令:
<div id="graph" style="width: 200px; height: 200px" canvasjs graphData="graph"></div>
这是我的指示:
publicApp.angularModule.directive('canvasjs', function () {
return {
restrict: 'A',
scope: {data : '=graphData'} ,
link: function (scope, element, attrs) {
scope.$watch('data', function (data) {
console.log(scope.data);
});
}
};
});
但scope.data未定义 . 我知道$ http.get是异步操作,但不应该是范围 . $ watch获取更新?
3 回答
尝试将值传递给指令:
canvasjs="graph"
.在我的例子中,我模拟来自服务和返回承诺的响应 .
HTML
JS
演示小提琴
如果您要在控制器中处理承诺:
您无需在服务中处理它:
如果您只想处理服务中的错误,那么您需要再次包装一个promise . 你可以使用
$q.when
:$q.when
将在对象周围包装一个承诺,如果它还不是一个承诺 .您无法在
success()
处理程序中返回数据并期望它返回 . 您必须链接另一个承诺(返回defer.promise()
),或在控制器中执行success
并修改结果中的$ scope . 或者只返回已经是承诺的整个$http
电话 .