简体   繁体   English

根据文档,无法在 angular ui-router 中访问 $state.current.data

[英]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.您有两个选项可以帮助解决此问题。

  1. You can create the directive without the 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.这里的缺点是这将指令的使用限制为每个范围的单个实例。
  2. Create a binding in the scope option and pass the variable from the HTML to the directive在 scope 选项中创建一个绑定并将变量从 HTML 传递给指令

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM