Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 823
metalaureate Avatar asked Nov 12 '14 22:11

metalaureate


1 Answers

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>

like image 160
Claies Avatar answered Oct 26 '22 00:10

Claies