使用 $http angularjs 在 factory 上观察 $scope

Watch $scope on factory using $http angularjs

我正在尝试观察使用 $http 从工厂获取的值的变化。

这是我的工厂:(它只是 returns 来自后端的视频列表)

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

对我做错了什么有任何见解吗?

要观看 $scope 元素,您必须执行以下操作:

$scope.$watch('educationalVideos', function (newValue, oldValue) {
    console.log(oldValue, newValue);
    if (newValue !== oldValue) {
        $scope.educationalVideos = newValue;
    }
});