【发布时间】:2017-12-06 08:50:27
【问题描述】:
我正在尝试使用 $http 观察从工厂获取的值变化。
这是我的工厂:(它只是从后端返回一个视频列表)
app.factory('videoHttpService', ['$http', function ($http) {
var service = {};
service.getEducationalVideos = getEducationalVideos;
return service;
function getEducationalVideos() {
return $http({
url: 'api/video/educational',
method: 'GET'
}).then(function (result) {
return result.data;
});
}
}]);
这是我的控制器:
app.controller('videoCtrl', ['$scope', 'videoHttpService',
function ($scope, videoHttpService) {
videoHttpService.getEducationalVideos().then(function (result) {
$scope.educationalVideos = result;
});
$scope.$watch($scope.educationalVideos, function (newValue, oldValue) {
console.log(oldValue, newValue);
if (newValue !== oldValue) {
$scope.educationalVideos = newValue;
}
});
}]);
这不起作用。我在console.log 中得到undefined、undefined。
对我做错了什么有任何见解吗?
【问题讨论】:
-
你需要 $watch 'educationalVideos' 而不是 $scope.educationalVideos。我不知道您的具体用例,但在您的请求之后使用额外的 .then() 块触发您的事件可能更有意义
标签: javascript angularjs http angularjs-scope factory