2016-03-15 63 views
0

我從服務器獲取數據與它被調用這個函數服務獲得VAR:angular.js從內部功能

LeadsSrv.async().then(function (d) { 
    results = d.data; 
}); 

我要訪問的結果,此功能之外,然後分配給它該範圍,就像這樣:

$scope.All_Leads = results; 

這裏是服務器功能:

LeadApp.service('LeadsSrv', function ($http) { 
    var all = { 
    async: function() { 
     var promise = $http({ 
      url: '../app/Data.php', 
      method: "POST", 
      params: { req_id: 'leads_list', user_id: 1 } 
     }).then(function (response) { 
     return response; 
     }); 
     return promise; 
    } 
    }; 
    return all; 
}); 

如何保險業監督請點這個?

+0

服務器功能是在Angular服務中調用還是在控制器中? – navigator

+0

我剛剛更新了我的問題與服務器功能 –

回答

3

您在腳本的開頭聲明變量,然後每當獲取數據的函數返回時,它就會更新該變量的值。

$scope.results = []; 

LeadsSrv.async().then(function (d) { 
    $scope.results = d.data; 
}); 

感謝角度是如何工作的,你不需要做任何事情,它也會更新UI元素和綁定。

更新:

我會做這種方式:

服務:

LeadApp.service('LeadsSrv', function ($http) { 
    var service = { 
     postData: postData 
    }; 

    return service; 

    function postData(data) { 
     return $http.post('../app/Data.php', data);  
    } 

在控制器:

//Initialize the variable 
$scope.results = []; 

var data = { 
    req_id: 'leads_list', 
    user_id: 1 
}; 

LeadsSrv.postData(data).then(function (response) { 
    //Once the $http.post succeeds, it will update your variable 
    $scope.results = response.data; 
}); 

這應該怎麼做你除非我誤解了你的問題,否則我一直在尋找Stion的。

+0

是你的解決方案的工作原理,但我從服務器的數據也得到了之前的工作,但我的問題是我怎麼現在可以訪問範圍外功能,以使其在我的整個網站? –

+0

@jhondano你能指定「整個網站」嗎?這一切都是角度,還是混合等? –

+0

該網站全是角度! –

0

我推薦你在下面的時間裏做這個。

根據LeadSrv對象使您的控制器/指令(擁有$ scope的人)。如果它不是一個「角度」組件已經包裝在工廠,然後將其注入您的控制器。

那麼你根本就

LeadsSrv.async().then(function (d) { 
    $scope.All_Leads = d.data; 
}); 
0

目前,你正在做正確的事情,除了的一個錯誤:您的電話是越來越異步執行。所以這基本上意味着,results將不會在您指向$scope.All_Leads時的預期值,因爲聲明是同步發生的。

要達到你想要的,你必須使用承諾。看看this和安格拉斯。

0

要檢查您的服務器是否報告錯誤,請添加.catch方法。

LeadsSrv.async().then(function onFulfilled(r) { 
    console.log("DATA: ", r.data); 
    $scope.results = r.data; 
}).catch(function onRejected(response) { 
    console.log("ERROR: ", response.status); 
});