【问题标题】:How to use $state.go on ng-submit如何在 ng-submit 上使用 $state.go
【发布时间】:2016-02-02 23:11:22
【问题描述】:

我在使用 AngularJS 和 Elasticsearch 构建的小型搜索应用的结果页面上有一个搜索表单。刚开始使用 ngRoute 的 UI-Router,需要弄清楚如何在我的 ng-submit 按钮上使用 $state.go() 以使搜索表单在结果页面上返回结果。

UI 路由器配置

$stateProvider
.state('search', {
  url: '/',
  views: {
    '': {templateUrl: 'templates/search.html'},//parent view
    'navbar@search': {templateUrl: 'templates/navbar.html', controller: 'TypeaheadCtrl'},
    'searchDisplay@search': {templateUrl: 'templates/results.html', controller: 'TypeaheadCtrl'},
    'pagination@search': {templateUrl: 'templates/pagination.html', controller: 'TypeaheadCtrl'}
  }
})

搜索表单

<form ng-submit="search()" class="navbar-form" id="global-search" role="search">
        <div class="input-group">
            <input type="text" name="q" ng-model="searchTerms" class="form-control input-md" placeholder="Search" id="search-input" uib-typeahead="query for query in getSuggestions($viewValue)" typeahead-on-select="search($item)" autofocus>
            <div class="input-group-btn">
                <button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
            </div>
        </div>
        </form>

我的 ng-submit 当前调用 search(),在我添加 $state.go() 后看起来像这样

$scope.search = function() {
resetResults();
$scope.filters.selectedFilters = [];

var searchTerms = $scope.searchTerms;

if (searchTerms) {
  $scope.results.searchTerms = searchTerms;
} else {
  return;
}

$state.go('/search', {term: $scope.searchTerms});

getResults();//uses service to get results data from search server

};

这会导致以下错误:错误:无法从状态“搜索”中解析“/搜索” 在 Object.y.transitionTo

不知道该怎么办,我仍然对 UI-Router 感到困惑。 只是想找出用于 ng-submit 发送搜索查询的最佳方法。有什么建议吗?

【问题讨论】:

    标签: javascript angularjs forms


    【解决方案1】:

    你应该在state.go而不是url中写状态名称:

    $state.go('search', {term: $scope.searchTerms});
    

    并添加您期望的查询参数:

    $stateProvider
      .state('search', {
        url: '/?term',
    ...
    

    【讨论】:

    • 所以我的查询会放在我的 app.js 文件中,其中配置了 ui-router?这与 ng-submit=search() 有什么关系?
    • @user3125823 使用 ui-sref 而不是 state.go 几乎总是更好的主意,因为当您添加 ui-sref 指令时,它会从目标状态解析 url 并将其添加到 href 属性。这是更好的选择,因为例如当您单击鼠标中键时,它将在新选项卡中打开(不适用于 state.go)。
    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多