admin管理员组

文章数量:1393059

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:

<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. Any ideas? Thanks!

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:

<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. Any ideas? Thanks!

Share Improve this question asked Nov 12, 2014 at 22:21 metalaureatemetalaureate 7,73211 gold badges59 silver badges97 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

The variable is indeed available to the page, but in your directive, you have created an isolated scope. whenever you use the scope: {} option on a directive, it creates a scope which is limited to the directive only.

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. 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

Directive: scope: {title: '=title'}

HTML: <title><page-title title="{{$state.current.data.title}}"></page-title></title>

本文标签: javascriptCan39t access statecurrentdata in angular uirouter as per documentationStack Overflow