2016-05-16 84 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>