[英]Can't access $state.current.data in angular ui-router as per documentation
I am trying to dynamically update the page title.我正在尝试动态更新页面标题。
Consider a state defined thus:考虑这样定义的状态:
$stateProvider.state('login', {
url: '/login',
templateUrl: '/templates/views/login.html',
controller: 'AuthCtrl',
data: {title: 'Log in'}
}
In the page HEAD section:在页面 HEAD 部分:
<title page-title></title>
According to the documentation, I am supposed to be able to access my custom data property :根据文档,我应该能够访问我的自定义数据属性:
app.directive("pageTitle", function ($state) {
return {
restrict: 'A',
template: "{{title}}",
scope: {},
link: function (scope, elem, attr) {
scope.title=$state.current.data.title; //wrap this in $watch
console.log('page state',$state.current.data.title);
}
}
});
But this returns undefined
.但这会返回
undefined
。 Any ideas?有任何想法吗? Thanks!
谢谢!
The variable is indeed available to the page, but in your directive, you have created an isolated scope .该变量确实可用于页面,但在您的指令中,您创建了一个隔离的 scope 。 whenever you use the
scope: {}
option on a directive, it creates a scope which is limited to the directive only.每当您在指令上使用
scope: {}
选项时,它都会创建一个仅限于该指令的范围。
You have two options which will help to solve this issue.您有两个选项可以帮助解决此问题。
scope:{}
option, which would allow the directive full access to the scope
which exists on the parent page.scope:{}
选项的指令,这将允许指令完全访问存在于父页面上的scope
。 The drawback here is that this limits the use of the directive to a single instance per scope.Directive: scope: {title: '=title'}
指令:
scope: {title: '=title'}
HTML: <title><page-title title="{{$state.current.data.title}}"></page-title></title>
HTML:
<title><page-title title="{{$state.current.data.title}}"></page-title></title>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.