1

У меня возникла проблема с AngularJS. Infact, так как мне нужно иметь «общую» переменную, читаемую и обновляемую в двух контроллерах, я думал об этом с фабрикой, введенной в обоих контроллерах. Данные загружаются через HTTP-запрос, но как только запрос завершен, var просто не обновляется. Вот мой код:AngularJS - Заводская переменная не обновляется в контроллере

//Common factory 
    app.factory('CurrentGallery',['$q','$http',function($q,$http){ 
    var data = null; 

    //HTTP request to API 
    var loadImages = function(query){ 
     $http.post("https://mywebsite.com/api/?"+query).then(function(result){ 
     update(result.data); 
     }); 
    } 

    //Update the data var 
    var update = function(data){ 
     data = data; 
     console.log("Update called", data); 
    } 

    return { 
     loadImages: loadImages, 
     update: update, 
     data: data 
    } 
    }]); 

    //The controller 
    app.controller("PhotoBestController", ['$scope', 'CurrentGallery', function ($scope,CurrentGallery) { 
    //$scope.pics is basically the variable I want to update inside my controller 
    $scope.pics = CurrentGallery.data; 

    //Send the data of the query for the API 
    CurrentGallery.loadImages("userInfo=true&exifInfo=true&order=tot_like,DESC"); 

    $scope.$watch(CurrentGallery, function(){ 
     console.log("CurrentGallery has changed"); 
    }); 
    }]); 

Это журнал я получаю в моей консоли:

  • CurrentGallery изменил
  • Update называется, Object {...}

Так это кажется, что CurrentGallery обновляется в первый раз, когда он равен нулю, но затем, даже если он обновляется внутри фабрики, он не обновляет переменную $ scope.pics var.

Любые предложения?

+0

это может помочь вам http://stackoverflow.com/questions/30596258/watch-factory-variable- с угловым –

+1

@VinodLouis, похоже, это не проблема! Он дает точно такой же результат, поэтому ничего не обновляется – Wendigo

ответ

0

UPDATE
Я следовал логике кода в этой теме: AngularJS : How to watch service variables?

app.factory('CurrentGallery',['$q','$http',function($q,$http) { 
    var updateCallbacks = []; 
    var data = null; 

    var loadImages = function(query) { 
    $http.post("https://mywebsite.com/api/?"+query).then(function(result) { 
     angular.forEach(updateCallbacks, function(callback) { 
     callback(result.data); 
     }); 
    }); 
    } 

    var registerUpdateCallback(callback) { 
    updateCallbacks.push(callback); 
    } 

    return { 
    loadImages: loadImages, 
    registerUpdateCallback: registerUpdateCallback 
    } 
}]); 

app.controller("PhotoBestController", ['$scope', 'CurrentGallery', function($scope,CurrentGallery) {  
    CurrentGallery.registerUpdateCallback(function(data) { 
    console.log("updated") 
    }); 
    CurrentGallery.loadImages("userInfo=true&exifInfo=true&order=tot_like,DESC"); 
}]); 
+0

Да, я думал об этом, но в случае, если я использую обещание, тогда как я могу обнаружить изменение в потенциальном 2-м контроллере, с которым я хочу поделиться текущим vargroup.data? – Wendigo

0
I think your data is updated in factory only. So for updating it in controller you have to get it again from the factory. 

So where you put watch in your controller re-assign the scope variable 

$scope.$watch(CurrentGallery, function(){ 
     $scope.pics = CurrentGallery.data; 
     console.log("CurrentGallery has changed"); 
}); 
+0

Это то, что я сделал, но он даже не запустил журнал «CurrentGallery has changed» – Wendigo

+0

Это не обязательно было в вашем коде, который вы разместили, так что я сохранил его здесь. Так это сработало или нет. –