从控制器中调用 angularjs ui-路由器状态

Calling an angularjs ui-router state from within a controller

我使用 angularjs ui-router 在应用程序中建立各种状态。虽然我知道我可以从 html 中的 link 进入状态(通过 ui-sref),是否有可能去控制器内的状态?

下面的代码片段是一个简单的 angularjs 应用程序,可以帮助说明我的观点。

在下面的例子中,我有两个状态:

  1. 有一个名为 home 的状态,它是一个简单的表单,包含一个文本输入字段和一个在控制器中调用搜索功能的按钮。
  2. 有一个名为 search 的状态,它接受一个名为 text 的查询参数。它的控制器调用一个基于文本执行搜索的服务。结果显示到页面。

首先是模块的初始化。

var app = angular.module('example', [
    'ui.router'
  ]);

下面是 ui-路由状态的配置,如前所述。

app.config(
  function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider.
      state('home', {
        url: '/',
        template: '<input ng-model="text" type="text" placeholder="Query Text">' +
          '<button type="button" ng-click="search()">Search</button>',
        controller: 'SearchFormController'
      }).
      state('search', {
        url: '/search?text',
        template: '<pre>{{results | json}}</pre>',
        controller: 'SearchController'
      });
  });

SearchFormController控制搜索的表单输入。该控制器只是将表单输入转发到 search 状态。 是否可以引用 search 状态而不是构造 URL 并调用 $location.path?

app.controller('SearchFormController', 
  function($scope, $location) {
    $scope.text = '';
    $scope.search = function() {
      // Can I use the 'search' state here instead of 
      // constructing a url and calling $location.path?
      $location.path('/search?text='+ encodeURIComponent($scope.text));
    };
  });

搜索控制器 SearchController 如下所示。它需要 stateParams(即查询参数)来发出 $http 调用。

app.controller('SearchController',
  function($scope, $stateParams, $http) {
    $scope.results = [];
    asUrl = function(resourceUrl, queryParams) {
      // do stuff and return http url
    };
    $http.get(asUrl("/someServiceUrl/search", $stateParams))
      .success(function(data, status) {
        $scope.results = data;
      })
      .error(function(data, status) {
        // display an error message
      });
  });

同样,在 SearchFormController 中,是否可以通过名称从配置中引用 search 状态?例如,在 html 页面中,我可以有这样一个 link: <a ui-sref="search({text:Foo})">Search where text=Foo</a> 其中 search 状态由名称引用并传入参数。是否可以从控制器调用类似的东西(按名称,传入参数)?

是的,检查文档:http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state $state.go(stateName, params, options)

go(to, params, options)

Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states).

我们可以使用许多设置,但所有这些都在上面的文档链接中明确定义

也可能很有趣:

Difference between ui-sref and $state.go in AngularJS UI-Router