【问题标题】:Take vaules from one JSON resoruce and using it to build another $resource with AngularJS从一个 JSON 资源中获取值并使用它通过 AngularJS 构建另一个 $resource
【发布时间】:2014-04-02 09:12:36
【问题描述】:

基本上,我有一个 SPA,它通过 JSON 从 Rails 站点获取其内容。现在我有一个工厂加载一个事件列表,其格式类似于:

{
id: 35987,
class: "Event",
event_id: 35987,
name: "New Event",
preview: "Description of the event goes here!"
},
{
id: 35989,
class: "Event 2",
event_id: 35989,
name: "Event for Something else",
preview: "Description of the event goes here again!"
}

然后,我在视图上显示前 5 个事件,控制器从资源中获取前 5 个事件。

  .controller('UpcomingCtrl', function($scope, upcomingFactory, localUserFactory) {

    localUserFactory.get(function (user) {
        upcomingFactory.query({channelID: user.channel_id}, function(data){
           $scope.upcomingEvents = data;
        });
    });

  })

这对我来说是棘手的部分。我希望用户能够点击这 5 个结果之一,然后被带到相应事件的详细信息页面。此详细事件的信息来自一个单独的 JSON 文件,该文件由使用此结构的事件 ID 标记http://www.testsite.com/api/v1/{{event_id}}.json

这意味着我需要以某种方式将事件列表中的事件 ID 传递给资源,并根据用户单击的 URL 为事件 .json 文件填写 {{event_id}}。这意味着路由也必须是动态的,这样当您单击链接时,http://www.testsite.com/events 上的任何事件都可以变为http://www.testsite.com/events/id

我希望这是有道理的!

【问题讨论】:

    标签: json angularjs angularjs-resource


    【解决方案1】:

    使用 url 映射器注册您的资源:

    $resource('testsite.com/events/:id);
    

    您可以通过向资源 get 调用提供对象来使用该 url 映射:

    myResource.get({id: oneId}).then(... 
    

    该对象中未在资源 url 中定义的任何其他属性将作为查询字符串参数放在请求 url 的末尾。

    编辑:

    我想我误解了你的问题。您可以使用我上面描述的相同 url 映射来注册您的应用程序路由。当用户点击一个事件时,做:

    $location.path(route + '/' + eventId);
    

    在细节控制器上,注入 $routeParams 服务并访问事件的 id 作为属性,例如:

    $scope.eventId = $routeParams.id // or instead of id, the name of the url mapping you registered in your routes ('events/:nameOfVariable') 
    

    【讨论】:

    • 我想我还是有点困惑。我确实已经通过.factory('eventFactory', function($resource) { return $resource('http://www.test.com/api/events/:eventID.json', {eventID: '@eventID'}, {'query': {method:'GET', isArray:false}}); }) 注册了我的路线 id 参数设置在那里,但是我如何从页面上的其他资源中获取这个 id 并将其准确推送到这个资源?另外,location.path 是否仅使用 ngclick?
    • 也许我误解了你的问题。您想将用户重定向到事件的详细视图吗?所以你希望用户去像 your-angular-site.com/eventDetail/{{eventId}} 这样的地方,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2016-09-23
    • 2017-06-02
    相关资源
    最近更新 更多