使用$ http angularjs观察工厂的$ scope

时间:2017-12-06 08:50:28

标签: javascript angularjs http angularjs-scope factory

我正在尝试使用$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;
        }
    });

}]);

这不起作用。我在undefined中获得undefinedconsole.log

对我做错了什么的见解?

1 个答案:

答案 0 :(得分:2)

要观看switch.isOn = !switch.isOn // 'onSwitchValueChanged' is not triggered元素,您必须执行以下操作:

$scope