我正在尝试观察使用 $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;
});
}
}]);
这是我的 Controller :
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
。
知道我做错了什么吗?
最佳答案
为了观察 $scope
元素,您必须执行以下操作:
$scope.$watch('educationalVideos', function (newValue, oldValue) {
console.log(oldValue, newValue);
if (newValue !== oldValue) {
$scope.educationalVideos = newValue;
}
});
关于javascript - 使用 $http angularjs 观看工厂上的 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47670192/