加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

从控制器内调用angularjs ui-router状态

发布时间:2020-12-17 17:45:38 所属栏目:安全 来源:网络整理
导读:我使用 angularjs ui-router来建立应用程序中的各种状态.虽然我知道我可以从html中的链接(通过ui-sref)进入状态,是否可以从控制器内进入状态? 下面的代码片段是一个简单的angularjs应用程序,以帮助说明我的观点. 在下面的示例中,我有两种状态: 有一个名为h
我使用 angularjs ui-router来建立应用程序中的各种状态.虽然我知道我可以从html中的链接(通过ui-sref)进入状态,是否可以从控制器内进入状态?

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

在下面的示例中,我有两种状态:

>有一个名为home的状态,它是一个简单的表单,包含一个文本输入字段和一个调用控制器中的搜索功能的按钮.
>有一个名为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控制搜索的表单输入.该控制器只是将表单输入转发到搜索状态.是否可以引用搜索状态而不是构造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',$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中,是否可以通过名称从配置中引用搜索状态?例如,在html页面中,我可以有这样的链接:< a ui-sref =“search({text:Foo})”>搜索text = Foo< / a>其中搜索状态由name引用并传入参数.是否可以从控制器调用类似的东西(通过名称,传入参数)?

解决方法

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

go(to,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).

我们可以使用许多设置,但所有设置都在上面的doc linke中明确定义

也可能很有趣:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读