【问题标题】:Passing parameters to the route on button click在按钮单击时将参数传递给路由
【发布时间】:2014-06-07 17:47:49
【问题描述】:

我是 AngularJs 的新手。我有一个带有按钮的搜索框,该按钮点击 Angular 应用程序配置中定义的路由。

<div class="search-block clearfix">
  <div class="input-group">
    <input type="text" placeholder="search here..."  class="form-control input-sm">
    <div class="input-group-btn">
      <button type="button" class="btn btn-default btn-sm" go-click="search.htm">Search</button>
    </div><!-- /btn-group -->
  </div><!-- /input-group -->
</div>

添加路由配置的代码sn-p:

myApp.config(function ($routeProvider){
  $routeProvider.
    .when('/search.htm',
     {
        controller:'controllers.SearchCtrl',
        templateUrl:'/partials/search/searchPage.html'
     })
    .otherwise({ redirectTo: '/' });
   ....

同时添加指令(go-click)代码:

    myApp.directive( 'goClick', function ( $location ) {
      return function ( scope, element, attrs ) {
        var path;
        attrs.$observe( 'goClick', function (val) {
        path = val;
      });
       element.bind( 'click', function () {
         scope.$apply( function () {
          $location.path( path );
      });
    });
  };
});

【问题讨论】:

  • 请显示路由配置。
  • 我已经用路由配置更新了帖子。控件进入控制器,但我无法将在搜索框中键入的关键字作为参数传递给控制器​​。

标签: angularjs angularjs-scope angularjs-routing


【解决方案1】:

您可以使用$route$routeParams 服务将参数传递给新路由。

如果您将路线更改为:

.when('/search.htm/:paramName',
     {
        controller:'controllers.SearchCtrl',
        templateUrl:'/partials/search/searchPage.html'
     })

并重定向到search.htm/someParam

那么参数someParam将作为服务$routeParams(包含参数的对象)或$route服务下的$route.current.params(这是同一个对象)在路由的控制器中可用。

docs 对此进行了介绍。

【讨论】:

    猜你喜欢
    • 2011-01-04
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2016-12-27
    • 2017-06-04
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多