2014-06-26 26 views
0

我是AngularJS的新手,現在我正在嘗試創建最簡單的Web應用程序,從服務器加載一些JSON數據。
它工作正常現在,看起來是這樣的:如何使用Angular加載更多內容(JSON)

JS文件

app.controller('myCont', ['$scope', '$http', function($scope, $http) { 
    $scope.moreItems = function() { 
     $http.post('php/index.php'). 
      success(function (data) { 
       $scope.posts = data; 
      } 
     ); 

     console.log('Button work'); 
    } 
}]); 

HTML

<div ng-controller="myCont"> 
    <span ng-click="moreItems()">Load more</span> 
    <ul> 
     <li ng-repeat="some in something">{{some.here}}</li> 
    </ul> 
</div> 

PHP產生一些JSON該頁面。每次它給我不同的數據。 但我的麻煩是,我不知道如何將更多的數據加載到該控制器。它總是取代它,但我想要連接它。

回答

0

每次從您的PHP服務器檢索數據時,您的代碼將覆蓋$ scope.posts變量。假設您的$ scope.posts var是一個對象,並且您要在調用moreItems()時添加新帖子,因爲在javascript中連接兩個對象是一項非常常見的任務,爲了不重新發明輪子,我鼓勵您使用_.extend underscore.js庫或類似的功能並

app.controller('myCont', ['$scope', '$http'], function($scope, $http) 
{ 
    $scope.moreItems = function() 
    { 
    $http.post('php/index.php'). 
     success(function (data) 
     { 
      _.extend($scope.posts, data); 
     } 
    ); 

    console.log('Button work'); 
}); 

http://underscorejs.org/#extend https://docs.angularjs.org/guide/scope

+0

嗨。感謝您的迴應!我包含underscode.js和更新JS代碼,但在我的情況下它不起作用。 –

+0

它報告什麼樣的錯誤? –

0

您可以使用angular.extend來連接你的數據。每當檢索到JSON數據時,它將與相同JSON對象中的先前數據連接起來。

注意:如果新傳入數據的組成屬性與先前JSON對象的屬性相同,那麼這些數據將被新數據覆蓋。如果要存儲屬性的舊數據,請確保傳入的數據包含不同的屬性。

app.controller('myCont', ['$scope', '$http', function($scope, $http) { 

    $scope.moreItems = function() 
    { 
     $http.post('php/index.php'). 
      success(function (data) 
       {      
        angular.extend($scope.posts, data) 
       } 
     ); 

     console.log('Button work'); 
    } 
}]); 

附加信息:如果你想存儲性能的以前的數據,那麼你可以使用瀏覽器本地存儲添加和retrive數據。這將使您免於進行多個數據庫調用。

添加數據:

localStorageService.add("postsData", JSON.stringify($scope.posts)); 

Retriveing數據:

$scope.posts = localStorageService.get("postsData"); 

有關browserlocalstorage更多信息不要讓我知道......

+0

我認爲你必須刪除'$ scope.posts = {}'。現在你正在清理'$ scope.posts'並添加新的東西,所以它不會保留你現有的數據。如我錯了請糾正我 :-)。 – Dieterg

+0

感謝您糾正它Dieter .. :) –