【问题标题】:Watch $scope on factory using $http angularjs使用 $http angularjs 在工厂观看 $scope
【发布时间】: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 中得到undefinedundefined

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

【问题讨论】:

  • 你需要 $watch 'educationalVideos' 而不是 $scope.educationalVideos。我不知道您的具体用例,但在您的请求之后使用额外的 .then() 块触发您的事件可能更有意义

标签: javascript angularjs http angularjs-scope factory


【解决方案1】:

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

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

【讨论】:

  • 我已对此进行了更新,但 oldValue 日志始终未定义。并且当一个视频被添加到列表中时,watch函数不会更新$scope,除非页面被刷新
  • “当视频添加到列表时”是什么意思。在您提供的代码中,您只需在控制器中进行一次 GET 调用。
  • 是的,我现在意识到我上面的例子并不完整,有时视频列表会更新。
  • 不过不用担心,您的回答帮助我解决了问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 2016-10-27
  • 2013-09-05
  • 1970-01-01
相关资源
最近更新 更多