javascript - 使用 $http angularjs 观看工厂上的 $scope

标签 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;
        });
    }
}]);

这是我的 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 中收到 undefinedundefined

知道我做错了什么吗?

最佳答案

为了观察 $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/

相关文章:

javascript - Angularjs动态设置属性

web-services - HTTP 上的 XML 和 HTTP 上的 SOAP 之间的区别

javascript - Worklight - 打开 native 应用程序

javascript - 在 WebView 中加载 HTML(以及未正确加载的 Javascript 源代码)- Swift

javascript - 如何在没有模板的情况下添加 View ?

performance - 使用 websockets 构建整个网站?重访

jsp - 如何从 JAX-RS 服务转发到 JSP?

php - .htaccess 拒绝除允许 javascript 访问之外的所有访问

javascript - 如何在 HTML 中显示函数的结果

javascript - HTML 选择 "Selected"属性不起作用