Unable to access $ state.current.data in angular ui-router according to documentation

I am trying to dynamically update the page title.

Consider a state defined this way:

$stateProvider.state('login', { url: '/login', templateUrl: '/templates/views/login.html', controller: 'AuthCtrl', data: {title: 'Log in'} } 

In the section of the HEAD section:

 <title page-title></title> 

According to the documentation, I should have access to the user 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!

+6
source share
1 answer

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

You have two options to help solve this problem.

  • You can create a directive without the scope:{} option, which allows the directive to have full access to the scope that exists on the parent page. The disadvantage here is that it limits the use of the directive for one instance for each scope.
  • Create a binding in the scope option and pass the variable from HTML to the directive

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

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

+7
source

Source: https://habr.com/ru/post/978114/


All Articles