我正在尝试动态更新页面标题。
考虑这样定义的状态:
$stateProvider.state('login', {
url: '/login',
templateUrl: '/templates/views/login.html',
controller: 'AuthCtrl',
data: {title: 'Log in'}
}
在页面的 HEAD 部分:
<title page-title></title>
根据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);
}
}
});
但这会返回 undefined
。有任何想法吗?谢谢!
最佳答案
该变量确实可用于页面,但在您的指令中,您创建了一个 isolated scope .每当你使用 scope: {}
指令上的选项,它创建一个仅限于指令的范围。
您有两个选项可以帮助解决这个问题。
- 您可以创建没有
scope:{}
的指令选项,这将允许指令完全访问scope
它存在于父页面上。这里的缺点是,这将指令的使用限制为每个范围的单个实例。 - 在范围选项中创建绑定(bind)并将变量从 HTML 传递到指令
指令:scope: {title: '=title'}
HTML:<title><page-title title="{{$state.current.data.title}}"></page-title></title>
关于javascript - 无法根据文档在 Angular ui-router 中访问 $state.current.data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26897788/