簡體   English   中英

使用$ http angularjs在工廠觀看$ scope

[英]Watch $scope on factory using $http angularjs

我正在嘗試觀察使用$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

對我在做什么錯有任何見解?

為了觀看$scope元素,您必須執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM