質問

I am creating a navigation, where when on the active 'link', a feed loads but with a different searched term.

Basically, the all the links are the same, the only difference is the term set in the .factory parameter.

Since everything is the same (even the .controller, is it possible to set the query term inside of the routeProvider, where I can specify the term that needs to be searched?

Or will the only way is to create a new controller for each link, and set the term inside of there? Keeping the code simple, efficient and as little as possible, is what I am trying to aim for.

  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);
        });
    }
  })

Thanks for any help in the right direction.

Roc.

役に立ちましたか?

解決

Using resource placeholders and $routeParams you define a hash URL which looks something like this <a href="#term/search+term+here">Term X</a>. The search term can be user input or a list of terms from database

  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
  })

Now when the route changes to a new term the resource is send new data parameters

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top