在ng-init和factory之间共享数据

时间:2016-10-01 15:23:52

标签: angularjs ng-controller ng-init

在我的应用程序中,我必须从init方法以递归方式检索工厂的数据集。如下所示.Ii尝试使用新的Factory对象,但是引发了错误Fact is undefinedinit方法中。

angular.module('name-App').factory('Fact', function(){
  return { Field: '' };
});


angular.module('name-App').factory('httpcall', function($http,$rootScope,$cookies,Fact) {

   return {

        getVal: function(stock) 
        {

             //return the promise directly.
             return  $http({
                                   url:'https://finance.google.com/finance/info?client=w&q='+stock, 
                                   method: "GET",
                                // params: {d1:st1,d2:st2}
                                  // params:{d:stock}
                           }).success(function(dx,status)
                            {   var metad =JSON.stringify(dx);
                                console.log("data in success metad.substring(3,metad.length-) ="+dx.substring(3,dx.length-1));
                                $rootScope.share=JSON.parse(dx.substring(3,dx.length-1));
                                // $rootScope.defStorage.push($rootScope.share);
                          Fact= $rootScope.share;//------->>>>>I NEED TO ACCESS THIS VALUE IN INIT METHOD
                                console.log(status+"-------JSON.stringify($scope.defStorage) ="+JSON.stringify($rootScope.defStorage));
                              //return result.dx;   
                            })
                             .catch(function(fallback) 
                             {
                              alert("failed in http call with ="+fallback + '!!');
                             });
    }
  }
});



$scope.init = function () {


        var ex=$cookies.get("arr") ;
        $scope.arry= JSON.parse(ex);


        //create a call to google api for all stocks in the $scope.arry
    $scope.arry.forEach(function(entry) {
    console.log("entry is "+entry);
    httpcall.getVal(entry);
    $scope.arry.push(Fact); // Fact not defined
    console.log("Fact"+Fact);
});

我可以通过其他方式访问$rootScope.share方法中的init吗?

1 个答案:

答案 0 :(得分:0)

您是否尝试使用构造函数创建工厂来启动它?

查看本教程:

Create Factory with parameters

希望有所帮助:)