2013-04-28 89 views
1

我有一个简单的页面,显示项目列表。数据从JSON文件中提取(URL由服务器提供)。角度加载json文件动态onclick

两个选项卡允许显示(onclick)“最新”或“流行”项目(每个选项卡的数据将通过JSON文件提供)。默认情况下,应该显示“最近的”项目。

加载正确的JSON文件onclick并显示其内容的最佳方式是什么?

我正在考虑在标记中传递URL(但我怀疑这是做到这一点的最佳方式)。

HMTL

<ul> 
    <li jsrc="recentitems.json" urlgetter>Most recent</li> 
    <li jsrc="popularitems" urlgetter>Most popular</li> 
</ul> 

Plunker我的代码: http://plnkr.co/edit/glSz1qytmdZ9BQfGbmVo?p=preview

对如何处理它的任何建议,我脑子里想的是什么?

编辑

我稍微改变我的做法。我现在正在做一个HTTP请求(希望更好的性能明智吗?)。 基本上我想加载所有的项目,然后过滤/排序它们。

从plunker扩大:http://plnkr.co/edit/glSz1qytmdZ9BQfGbmVo?p=preview 我添加了一个“日” &“意见”属性到对象的项目(见JSON)。

  1. 标签 - 我怎么能过滤/项目的onclick排序? “最近”将按日期排序,“流行”将按视图排序。
  2. 类别 - 我使用ng-click获取类别值,但不知道如何动态更新过滤器(使用传递的onclick值)。

感谢

回答

7

一种方式是做这样的事情: -

首先HTML: -

<div ng-app="App"> 
     <div ng-controller="tabsCtrl"> 
     <ul> 
      <li ng-click="tab(1)">Recent items</li> 
      <li ng-click="tab(2)">Popular items</li> 
     </ul> 
     <ul> 
      <li ng-repeat='product in products'>{{product.Name}}</li> 
     </ul> 
     {{products || json}} 
     </div> 
    </div> 

和JS

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

app.factory('products', function ($http, $q) { 
     return { 
     items: function (url) { 
      //create our deferred object. 
      var deferred = $q.defer(); 

      //make the call. 
      $http.get(url).success(function (data) { 
       //when data is returned resolve the deferment. 
       deferred.resolve(data); 
      }).error(function() { 
       //or reject it if there's a problem. 
       deferred.reject(); 
      }); 

      //return the promise that work will be done. 
      return deferred.promise; 
     } 
     } 
    }); 

app.controller("tabsCtrl", function ($scope, products) { 
    $scope.products = products.items('/api/products'); 

    $scope.tab = function (tabIndex) { 
     if (tabIndex == 1) 
     $scope.products = products.items('/api/products'); 
     if (tabIndex == 2) 
     $scope.products = products.items('/api/popularproducts'); 
    }; 
}); 
+0

很抱歉这么晚才回复。首先感谢您的回应。经过第二次考虑后,我略微改变了方法。我最初的想法是从服务器为每个选项卡(最新和最流行)获取一个JSON文件,但由于Angular过滤器似乎很强大,我想利用它。我还有一些问题 - 希望没关系。看我的**编辑**;还添加了一些意见,我的更新plunker http://plnkr.co/edit/glSz1qytmdZ9BQfGbmVo?p=preview – John 2013-05-01 23:47:19

+0

Urm,实际上答案正是你最初的要求。真的,你应该为你的编辑提出另一个问题,因为它已经发生了巨大的变化。我很抱歉你没有奖励我的努力。祝你好运 – Rippo 2013-05-02 06:17:42

+0

没问题。我认为可以问这里,因为它是相关的,但我会问一个新问题。非常感谢。 – John 2013-05-02 07:52:56