【问题标题】:Trying to append a REST url in Angular upon button click.尝试在单击按钮时在 Angular 中附加一个 REST url。
【发布时间】:2017-01-09 01:11:26
【问题描述】:

所以我在 Ionic 框架中设置了以下工厂/控制器,它工作正常。但是,我想提供三个单击后更改位置的按钮 - 例如按钮一 = 伦敦,按钮二是纽约,按钮三将其更改为马德里。我目前可以通过编写三个工厂并更改 API URL 来做到这一点 - 硬编码它,但它看起来很乱。我想知道是否有一种方法可以将“点击”链接到参数或其他东西?我搜索过,也看过搜索、插值和 $resource 教程,但似乎没有什么是完全正确的。

.factory('eventService', function ($http) {
    var events = [];

    return {
        getEvents: function () {
            return $http.get('http://api.API.com/json/q=music&location=LONDON&app_key=XXX').then(function (response) {
                events = response.data.events;
                return response.data.events;
            });
        },
        getEvent: function (index) {
            return events.event[index];
        }
    }
})

//控制器

      .controller("GigsCtrl", function ($scope, eventService) {
        eventService.getEvents().then(function (events) {
            $scope.events = events;
        });
    })

//每个项目都是可点击的等等...

    .controller("GigDetailCtrl", function ($scope, $stateParams, eventService) {
        $scope.event = eventService.getEvent($stateParams.index);
        console.log("Second Controller says: Hello World - I work");
    })

这可能是一个非常简单的解决方案,我就是只见树木不见森林!温柔点,我从 12 月才开始这样做,所以对它很陌生!

这已经非常接近但仍然没有真正解决...Get URL param in Express API from Angular UI-Router

//按钮 - 每个都进入一个新的搜索页面,目前每个都有一个工厂,但理想情况下我会点击按钮来更改一个“主”工厂...

<ion-content class="padding">
    <div class="button-bar bar-dark">
        <a href="#/london" class="button">London</a>
        <a href="#/madrid" class="button">Madrid</a>
        <a href="#/newyork" class="button">New York</a>

【问题讨论】:

  • 凯尔。请阅读您的帖子一次并有意义地改写它,以及您面临的麻烦是什么?更新它以发布

标签: angularjs rest ionic-framework


【解决方案1】:

可以传入修改请求url所需的值,比如:

getEvents: function (location) {

    var params ={
       q:'music',
       app_key: your_app_key,
       location: location ? location.toUpperCase() :'LONDON';//default
    };
     return $http.get('http://api.API.com/json/', {params: params}).then(function (response) {             
         return response.data.events;
     });
 }

然后在您的状态配置中使用位置而不是索引以获得更有意义的 url 显示

【讨论】:

  • 啊,差不多了 - 它是如此接近,但它会如何看待事物的 HTML/Button 方面?我只是不太明白如何将参数链接到按钮单击...
  • 您使用$stateParams 并在您的状态配置中配置相同的url...配置中的url 看起来像url: 'music-list/:location' 并在html 中使用ui-sref="music-list-stateName({location:'MADRID'})"
  • 我明白了!就像我对 GigDetailCtrl 页面所做的一样......我会试试的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-12-26
  • 2019-08-12
  • 2017-04-05
  • 2022-01-05
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多