将 $state 和 $stateParams 的引用添加到 Typescript(角度)中的 $rootScope
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27764930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add reference to $state and $stateParams to $rootScope in Typescript (angular)
提问by xvdiff
I'm trying to set the page title of my angular app based on data of the current state (configured in ui-router).
我正在尝试根据当前状态的数据(在 ui-router 中配置)设置我的 angular 应用程序的页面标题。
<title ng-bind="$state.current.data.pageTitle></title>
On this link, I found the following to add a reference to $state/$stateParams to the root scope:
在此链接上,我发现以下内容将 $state/$stateParams 的引用添加到根范围:
.run([ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
How can I translate this to typescript?
我怎样才能把它翻译成打字稿?
function run($rootScope: ng.IRootScopeService, $state : ng.ui.IState, $stateParams : ng.ui.IStateParamsService) {
$rootScope.$state // 'state' cannot be resolved
}
回答by Radim K?hler
UPDATE: previous version of this answer would not be working with a angular strict mode, or minification.
更新:此答案的先前版本不适用于角度严格模式或缩小。
I would therefore suggest to add this ng-strict-didirective into index.html:
因此,我建议将此ng-strict-di指令添加到index.html 中:
<html data-ng-app="App" ng-strict-di> // see ng-strict-di
<head>
And that would reveal that the proper way is:
这将表明正确的方法是:
module App
{
export class RootConfig
{
static inject = ['$rootScope', '$state', '$stateParams'];
constructor(
$rootScope: any, //ng.IRootScopeService,
$state: ng.ui.IStateProvider,
$stateParams: ng.ui.IStateParamsService)
{
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
}
}
angular.module('App')
// wrong - not working in minified world
// .run(App.RootConfig);
// correct
.run(['$rootScope', '$state', '$stateParams', App.RootConfig]);
Why this $rootScope: any, //ng.IRootScopeService,
instead of this: $rootScope: ng.IRootScopeService,
? To make life easier... and quickly assign not declared properties $state
and $stateParams
为什么是这个$rootScope: any, //ng.IRootScopeService,
而不是这个:$rootScope: ng.IRootScopeService,
?为了让生活更轻松......并快速分配未声明的属性$state
和$stateParams
回答by Maruf
I found a cleaner route than setting it to any
我找到了比将其设置为更清洁的路线 any
declare module app {
interface IScope extends ng.IScope {
$root:IRootScopeService
}
interface IRootScopeService extends ng.IRootScopeService {
$state:ng.ui.IStateService
}
}
Then to use it just declare like
然后使用它只需声明像
constructor(
$rootScope: app.IRootScopeService,
$state: ng.ui.IStateProvider
{
$rootScope.$state = $state;
}