我有一个搜索字段,当我单击搜索按钮时,我将使用在搜索字段中输入的值对数据进行搜索。这是我的代码。

HTML代码

<a href="#/home">Home</a>
<label class="item item-input">
    <input type="text"><a ng-href="#/search/{{searchVal}}" ng-model="searchVal">Search</a>
</label>


JS代码

angular.module('myApp', ['ngRoute'])
 .controller('searchController', function($scope, $http, $routeParams) {
    var name = $routeParams.name;
    alert(name)
});

angular.module('myApp')
  .config(function($routeProvider) {
    $routeProvider.
      when('/home', {
        templateUrl: 'home.html'
      }).
      when('/search/:name', {
        templateUrl: 'search.html',
        controller: 'searchController'
      }).
      otherwise({
        redirectTo: '/home'
      });
});


在这里,我无法将搜索值传递给routeProvider。如何通过routeProvider传递搜索值并在searchController中访问它。

我在控制器中使用了routeParams,但是我无法检索搜索字段的值。

那么,如何在searchController中获取值?这是Plnkr

最佳答案

您应在路由定义中定义search参数,以使routeParams能够识别参数。

when('/search/:name', {
    templateUrl: 'search.html?query',
    controller: 'searchController'
})


您可以使用routeParams.query在控制器中检索值。

10-06 04:18
查看更多