2016-05-16 44 views
2

首先,這是我第一次與Angular合作。AngularJS加載JSON數據,然後從它解析/加載HTML

我的目標是實現的是,我有一個通知列表,我以某種方式必須限制limitTo,所以元素被限制爲三個,點擊按鈕後,其餘的應該加載。

我不什麼明白怎麼做:

  • 成立「視圖」以及如何應用NG-重複
  • 負荷,我已經設置了,不知怎麼的JSON數據解析它作爲純HTML從* json進入視圖
  • 在一切順利之後,使用limitTo,因此我可以將項目從開始時限制爲3,並且在單擊該按鈕之後,我希望其餘部分在下面加載。

我請求幫助,這是我一直到的。

示例代碼,因爲這麼需要它:

var app = angular.module('notifyApp', []); 

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

$http({ 
    method: 'GET', 
    url: 'notifications.json' 
}).success(function(){ 
    console.log('success'); 
}).error(function(){ 
    console.log('error'); 
}); 

$scope.loadmore = true; 
}); 

這裏是一個Plunker

預先感謝您!

+0

你是否完成了在angularjs網站上的教程?它很好地演示瞭如何做到這一切,包括如何使用ngAnimate。 –

回答

0

我有一個解決方案。試試你的plnkr。

注意我是如何硬編碼的$scope.notifications。你會想要檢索實際的數據 - 不知道如何在plnkr中做到這一點。當你檢索JSON的時候,你將不得不信任這樣的數據:

var app = angular.module('notifications', []); 
app.controller('mainController', function($scope, $http, $sce) { 
    $http({ 
     method: 'GET', 
     url: 'notifications.json' 
    }).success(function(data){ 
     console.log('success'); 
     $scope.notifications = data; 
     for (var i=0; i<$scope.notifications.length; i++){ 
      $scope.notifications[i].userAction = $sce.trustAsHtml($scope.notifications[i].userAction) 
     } 
    }).error(function(data){ 
     console.log('error'); 
    }); 
    $scope.myLimit = 3; 

    $scope.loadmore = true; 
}); 

編輯,因爲也許解釋是應該的。以下是我所做的更改:

  • Angular Module發生錯誤(名稱錯誤),所以我更改了JS的第一行。
  • $scope.notifications必須在JS中聲明。
  • 新增$ scope.myLimit所以我們可以修改這個變量limitTo
  • 在NG-點擊,除去notifications = !notifications,加入myLimit = notifications.length所以它可以顯示所有結果。
  • 最後,添加了ng-bind-html而不是{{notification.userAction}},因此它可以顯示爲HTML。

JS:

var app = angular.module('notifications', []); 

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

$http({ 
    method: 'GET', 
    url: 'notifications.json' 
}).success(function(){ 
    console.log('success'); 
}).error(function(){ 
    console.log('error'); 
}); 

$scope.notifications = [ 
{ 
    "avatar" : "images/otherUser.png", 
    "type" : "", 
    "userName" : "Ivana Stankova", 
    "userAction" : "<span class=\"heart\">&#10084;</span>&nbsp;your photo", 
    "targetObject" : "images/targetPhoto.jpg" 
}, 
{ 
    "avatar" : "images/otherUser2.png", 
    "type" : "", 
    "userName" : "Ivana Stankova", 
    "userAction" : "<span class=\"heart\">&#10084;</span>&nbsp;your photo", 
    "targetObject" : "images/targetPhoto.jpg" 
}, 
{ 
    "avatar" : "images/otherUser4.png", 
    "type" : "checkedIn", 
    "userName" : "Dave Peters", 
    "userAction" : "Checked in<br/><a href=\"#\">962 Grant Street Victoria</a>", 
    "targetObject" : "images/place.jpg" 
}, 
{ 
    "avatar" : "images/otherUser4.png", 
    "type" : "commented", 
    "userName" : "Dave Peters", 
    "userAction" : "Commented on <a href=\"#\">your post</a><p>Hey guys,&nbsp8 o’clock? Let’s get some food first? How<br/>about that fancy restaurant we wanted to try for...</p>", 
    "targetObject" : "images/targetPhoto.jpg" 
}, 
{ 
    "avatar" : "images/otherUser.png", 
    "type" : "", 
    "userName" : "Ivana Stankova", 
    "userAction" : "<span class=\"heart\">&#10084;</span>&nbsp;your photo", 
    "targetObject" : "images/targetPhoto.jpg" 
}, 
{ 
    "avatar" : "images/otherUser.png", 
    "type" : "", 
    "userName" : "Ivana Stankova", 
    "userAction" : "<span class=\"heart\">&#10084;</span>&nbsp;your photo", 
    "targetObject" : "images/targetPhoto.jpg" 
}, 
{ 
    "avatar" : "images/otherUser4.png", 
    "type" : "", 
    "userName" : "Dave Peters", 
    "userAction" : "<a href=\"#\">Made a new post.</a>", 
    "targetObject" : "images/targetPhoto.jpg" 
}, 
{ 
    "avatar" : "images/otherUser.png", 
    "type" : "", 
    "userName" : "Ivana Stankova", 
    "userAction" : "Started following you.", 
    "targetObject" : "" 
}, 
{ 
    "avatar" : "images/fivePeople.png", 
    "type" : "", 
    "userName" : "", 
    "userAction" : "Five people Started following You.", 
    "targetObject" : "" 
} 
] 

$scope.myLimit = 3; 

    $scope.loadmore = true; 
}); 

的Index.html

+0

Downvote的原因是什麼? – chakeda

+2

有人降低了另一種解決方案。作爲一項傳統,我向所有參與者致敬。不是我。 – snkv

+0

任何想法如何使用ngAnimate,這樣我就可以使用ng-repeat出現每個動畫,或者我應該堅持使用css動畫? – snkv

0

首先,你應該使用then() promisse代替success()error()。這是應該使用promisses目前的方式。

您可以在ng-repeat屬性中使用'limitTo = val'限制您的nrRepeat循環。

我做了一個片段向你展示你的問題的解決方案:

var myApp = angular.module('myApp', []); 
 

 
myApp.controller('myAppController', ['$scope', function($scope){ 
 
    $scope.defaultLimit = 3; // the default limit 
 
    $scope.list = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6', 'item 7']; 
 
    $scope.showAll = function(){ 
 
    $scope.defaultLimit = $scope.list.length; // show all reccords 
 
    } 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="myApp"> 
 
    <div ng-controller="myAppController"> 
 
    <ul> 
 
     <li ng-repeat="item in list | limitTo:defaultLimit">{{item}}</li> 
 
    </ul> 
 
    <button ng-click="showAll()" type="button">Show all</button> 
 
    </div> 
 
</div>

+0

所以你要創建一個作用域,它被分配給json列表,並在其上附加「length」,這是另一種方式。礦是不必要的複雜的權利?儘管我沒有完全理解,但我發現它在Google的某個地方。 – snkv

+1

我不會說你的是不必要的複雜,而是有點錯誤。如果有的話,這更像是一個偏好問題。 –

+1

這裏的要點是用於限制ng-repeat的'$ scope.defaultLimit'變量。它的默認值是3,如你所願。我所做的就是將這個變量賦給它的數組長度,所以你的限制將是整個數組。 – vinagreti

1

你plunker有幾個錯誤。

首先,你的index.html中ng-app應該notifyApp,因爲這是你在你的script.js設置什麼 - var app = angular.module('notifyApp', []);

其次:你必須分配你的成功的功能您的通知$scope.notifications

$http({ 
    method: 'GET', 
    url: 'notifications.json' 
}).then(function(res){ 
    $scope.notifications = res; 
}); 

之後,您應該已經看到前3個元素。

您需要做的最後一件事是從加載更多按鈕的ng-click屬性中刪除notifications = !notifications

修改的Plunker here

+0

這清除了事情。這與我之前嘗試做的接近,但在這種情況下,它的工作原理。非常感謝你! – snkv

1

設置視圖並使用ng-repeat。

你想存儲的通知某處(可能是一個數組),然後使用NG重複=「數據yourArray」在HTML文件中的標記(DIV例如)之內。如果你想顯示特定的通知,你可以應用過濾器。在你的情況下,你想最初顯示3,然後如果點擊一個按鈕移動到其餘的。您可以創建一個單獨的數組,存儲前3個通知,另一個包含整個數組,並使用ng(如果在您的標記中顯示結果)。

var myApp = angular.module('myApp', []); 
 

 
myApp.controller('notificationController', ['$scope', 
 
    function($scope) { 
 
    $scope.buttonNotClicked = true; 
 

 
    $scope.fullArray = [item1, item2, item3, item4, item5]; 
 
    $scope.partialArray = [fullArray[0], fullArray[1], fullArray[2]]; 
 

 

 
    function onButtonClick() { 
 
     $scope.buttonNotClicked = false; 
 
    } 
 
    } 
 
]);
<div ng-if="buttonNotClicked"> 
 
    <div ng-repeat="data in partialArray"></div> 
 
</div> 
 

 
<div ng-if="!buttonNotClicked"> 
 
    <div ng-repeat="data in fullArray"></div> 
 
</div>

How to use parameters within the filter in AngularJS?

1

所以第一步是在成功回調,你應該保存,然後返回數據在你的範圍的地方,如:

.success(function (data) { 

    $scope.myList = data; 

    $scope.myListLimit = 3; // lets also set a limit for our list 
} 

然後,你可以把你的視圖寫成指向ng-controller指令的元素的後代:

<div ng-controller="mainController"> 
    <ul ng-repeat="item in myList | limitTo: myListLimit"> 
    <li>{{item}}</li> 
    </ul> 
    <button type="button" ng-show="anyResultsPending()" ng-click="showMoreResults()">Show more results</button> 
</div> 

之後,你的清單應與3周的結果顯示,並能顯示更多的用戶交互的結果,我們在控制器上創建一個新方法:

$scope.showMoreResults = function() { 

    $scope.myListLimit += 3; 
} 

// this is to hide the "show more results" button after the all items was shown 
$scope.anyResultsPending = function() { 

    return $scope.myList && $scope.myListLimit < $scope.myList.length; 
} 
1

在另外,正如AngularJS : Insert HTML into view, 中所解釋的,當使用JSON中包含的HTML時,您需要進行清理。使用此模塊:

<script src="bower_components/angular-sanitize/angular-sanitize.js"></script> 

在你的JS,我很驚訝,這似乎是因爲添加依賴簡單:

var ricksiteControllers = angular.module('ricksiteControllers', ["ngSanitize"]); 

    ricksiteControllers.controller('PagesCtrl', ['$scope', 'Page', 
      function($scope, Page) { 
       $scope.pages = Page.query(); 
    }]); 

我的服務。JS有角資源代碼:

var ricksiteServices = angular.module('ricksiteServices', ['ngResource']); 

ricksiteServices.factory('Page', ['$resource', 
    function($resource){ 
    return $resource('pages/:pageId.json', {}, { 
     query: {method:'GET', params:{pageId:'pages'}, isArray:true} 
    }); 
    }]); 
// actually, the pageID parameter has only one value, only the default 'pages' is used. 
+0

我早些時候嘗試過使用它,但是我沒有獲得太多的成功。我需要做些什麼才能使其工作?將它作爲模塊中的依賴添加,[]? – snkv

+1

答案現在更新爲顯示JS。可疑簡單。 – rleir

+0

在我的情況:var app = angular.module('notifications',[「ngSanitize」]);其次是第二個.controller片段,但似乎不起作用。我哪裏去了非常錯誤? – snkv

1

下面是做什麼的一些其他的答案沒有提供一個解決方案:

  • 動畫
  • 負載直接從使用的角度工廠的JSON和對象承諾
  • 限制3項目並加載上的按鈕,其餘點擊

的JavaScript:

(function() { 
    "use strict"; 

    var module = angular.module('app', ['ngAnimate']); 

    module.factory('NotificationsService', ['$http', function ($http) { 
     return { 
      fetch: function() { 
       return $http.get('notifications.json').then(function (response) { 
        return response.data 
       }); 
      } 
     }; 
    }]); 

    module.controller('Controller', ['$scope', '$filter', 'NotificationsService', function ($scope, $filter, NotificationsService) { 
     $scope.notifications = []; 
     $scope.limit = 3; 
     $scope.allLoaded = false; 

     NotificationsService.fetch().then(function (data) { 
      $scope.notifications = data; 
     }); 

     $scope.loadAll = function() { 
      $scope.limit = $scope.notifications.length; 
      $scope.allLoaded = true; 
     }; 
    }]); 
})(); 

HTML/CSS

<!doctype html> 
<html ng-app="app"> 

<head> 
    <title>ng-limit</title> 

    <style> 
     .my-repeat-animation.ng-enter, 
     .my-repeat-animation.ng-leave, 
     .my-repeat-animation.ng-move { 
      -webkit-transition: 0.5s linear all; 
      transition: 0.5s linear all; 
      position: relative; 
     } 

     .my-repeat-animation.ng-enter { 
      top: -20px; 
      opacity: 0; 
     } 

     .my-repeat-animation.ng-enter.ng-enter-active { 
      top: 0; 
      opacity: 1; 
     } 

     .my-repeat-animation.ng-leave { 
      top: 0; 
      opacity: 1; 
     } 

     .my-repeat-animation.ng-leave.ng-leave-active { 
      top: -20px; 
      opacity: 0; 
     } 

     .my-repeat-animation.ng-move { 
      opacity: 0.5; 
     } 

     .my-repeat-animation.ng-move.ng-move-active { 
      opacity: 1; 
     } 
    </style> 

    <script src="node_modules/angular/angular.js"></script> 
    <script src="node_modules/angular-animate/angular-animate.js"></script> 
    <script src="app.js"></script> 
</head> 

<body ng-controller="Controller"> 
    <button ng-show="!allLoaded" ng-click="loadAll()">Load all</button> 
    <div ng-repeat="notification in notifications | limitTo:limit" class="my-repeat-animation"> 
     <div> 
      <h4>Notification: {{$index+1}}</h4> 
      <div> 
       Avatar: {{notification.avatar}} 
      </div> 
      <div> 
       Type: {{notification.type}} 
      </div> 
      <div> 
       Name: {{notification.userName}} 
      </div> 
      <div> 
       Action: {{notification.userAction}} 
      </div> 
      <div> 
       Target: {{notification.targetObject}} 
      </div> 
     </div> 
    </div> 
</body> 

</html>