Updating a variable scope for multiple controllers in angularjs

I have two controllers - searchBoxController and productList. What I'm trying to do is update the scope scope.products variable from multiple controllers. I know that defining it as a root variable is a very poor design, but using this in a shared service does not solve the problem. The update is not reflected in the HTML templates!

function SearchTermService(){
    this.productSearch = function(data, $http){
        var url = "";
        $http.get(url).then(function(resp){
            return resp.data;
        },
        function(err){
            console.log(err);
        });
    };
};

var app = angular.module('app', []);
app.service("myService", MyService);
app.service("searchTermService", SearchTermService);
app.run(function($rootScope) {
    $rootScope.products = new Date();
});

app.controller('productList', function ($scope, $rootScope, $http, myService) {
    $rootScope.products = prod_res;
});



app.controller('searchBoxController', function($scope, $http, searchTermService, $rootScope){
        $scope.getSearchResults = function(){
        $rootScope.products = searchTermService.productSearch($scope.term, $http)
    };
});

PS: I'm not sure that I need to return the promise when assigning $ rootScope.products to 'searchBoxController', since console.log says it is undefined. Currently, I am not returning a promise from the service.

+4
source share
1 answer

, angular.

, angular , , .

, . factory , , . , .

(function(){

function Controller($scope, $timeout, Service) {

  //Retrieve current data object of our service
  $scope.data = Service.value;

  //will be set to 4
  $timeout(function(){
    Service.set(4, 'product');
  }, 1000);

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();


(function(){

function Controller2($scope, $timeout, Service) {

  //Retrieve current data object of our service
  $scope.data2 = Service.value;

}

angular
.module('app')
.controller('ctrl2', Controller2);

})();

(function(){

  function Service() {

    //Our data object
    var data = {
      product: null
    };

    function set(value, field){
      data[field] = value;
    }

    return {
      set: set,
      value: data
    };


  }

  angular
    .module('app')
    .factory('Service', Service);

})();

HTML

  <body ng-app='app'>

    <div ng-controller='ctrl'>
      <h2>Service value : {{data.product}}</h2>
    </div>

    <div ng-controller='ctrl2'>
      <h2>Service value from controller2 : {{data2.product}}</h2>
    </div>

  </body>

, . , $rootScope.

+10

Source: https://habr.com/ru/post/1608490/


All Articles