【问题标题】:AngularJS - Changing a query param term within $routeProvider?AngularJS - 在 $routeProvider 中更改查询参数项?
【发布时间】:2013-09-22 16:52:40
【问题描述】:

我正在创建一个导航,当在活动的“链接”上时,会加载一个提要,但搜索词不同。

基本上所有的链接都是一样的,唯一不同的是.factory参数中设置的术语。

既然一切都是一样的(即使是.controller,是否可以在routeProvider内部设置查询词,我可以在其中指定需要搜索的词?

或者唯一的方法是为每个链接创建一个新的控制器,并在那里设置术语?保持代码简单、高效和尽可能少,是我努力的目标。

  angular.module('termSearch', ['ngResource'])

  .config(['$httpProvider', function ($httpProvider) {
      $httpProvider.defaults.headers.common["X-Requested-With"] = undefined;
  }])

  .config(function($routeProvider) {
    $routeProvider
      .when('/term1', {templateUrl: 'views/feedlist.html', controller: 'searchtermCtrl' })      
      .when('/term2', {templateUrl: 'views/feedlist.html', controller: 'searchtermCtrl' })

      .otherwise({redirectTo: '/term1'});
  })

  .factory('Feed', function ($resource) {
      return $resource('https://www,example.com/:term/json', {}, {
          query: {
              method: 'GET',
              isArray: false,
              params: {
                  term: "term#"
              }
          }
      });  
  })

  .controller('searchtermCtrl', function($scope, Feed){
    $scope.results = Feed.query();
    $scope.feed = function (term) {
        Feed.get({
            term: term
        }, function (results) {
            $scope.results = results
            console.log(results);
        });
    }
  })

感谢您在正确方向上的任何帮助。

罗克

【问题讨论】:

    标签: angularjs controller factory route-provider


    【解决方案1】:

    使用资源占位符和 $routeParams,您可以定义一个类似于 <a href="#term/search+term+here">Term X</a> 的哈希 URL。搜索词可以是用户输入或数据库中的词列表

      angular.module('termSearch', ['ngResource'])
    
      .config(['$httpProvider', function ($httpProvider) {
          $httpProvider.defaults.headers.common["X-Requested-With"] = undefined;
      }])
    
      .config(function($routeProvider) {
        $routeProvider
          .when('/term/:q', {templateUrl: 'views/feedlist.html', controller: 'searchtermCtrl' })      
    
          .otherwise({redirectTo: '/term/'});
      })
    
      .factory('Feed', function ($resource) {
          return $resource('https://www.example.com/:term/json', {}, {
              query: {
                  method: 'GET',
                  isArray: false
              }
          });  
      })
    
      .controller('searchtermCtrl', function($scope, Feed, $routeParams){
        $scope.feed = Feed.query({ term : $routeParams.q }); // This will get the term from url
      })
    

    现在,当路由更改为新术语时,资源将发送新的数据参数

    【讨论】:

    • 谢谢蒂姆!甚至比我预期的要少的编码,并且非常彻底地遵循。也是仅供参考或其他任何人,作为参考,以.factory $resource URL 内部的:term 为目标,将.controller $scope 内部的feed: 换成term:,否则新查询将添加到$resource URL 结束,再次感谢!
    • #angularjs 上有一个非常好的tutorial,它将为您提供所有基础知识以及它们如何协同工作。为一个好的 javascript 框架干杯
    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多