Javascript 使用角度和角度路线扩展动态标题
我过去习惯于动态设置应用程序的标题。有一种解决方案几乎完全有效,只有一种情况例外。以下是我的路由器:Javascript 使用角度和角度路线扩展动态标题,javascript,angularjs,angular-routing,Javascript,Angularjs,Angular Routing,我过去习惯于动态设置应用程序的标题。有一种解决方案几乎完全有效,只有一种情况例外。以下是我的路由器: app.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/', { templateUrl: '/partials/home.html', controller: 'home', title: "Corvid"
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/partials/home.html',
controller: 'home',
title: "Corvid"
})
.when('/archive', {
templateUrl: "/partials/archive/all.html",
controller: "archive",
title: "Archive"
}).
when('/archive/:id', {
templateUrl: "/partials/archive/one.html",
controller: "article",
title: ""
})
.otherwise({
templateUrl: "/partials/errors/404.html",
title: "Something went wrong!"
});
}
]);
app.run(['$location', '$rootScope',
function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
$rootScope.title = current.$$route.title;
});
}
]);
当使用预定义的和具体的字符串时,比如Corvid,它将非常好地工作。然而,对于/archive/:id的情况,我想要更随意的东西;文章的标题。也就是说,/archive/2/将标题设置为“突发新闻”;corvid在angular.js上很烂。这是我的产品工厂:
services.factory('Article', ['$resource', function($resource) {
return $resource('/api/v1/articles/:articleId', {}, {
query: { method: 'GET', params: { articleId: '' } }
});
}
]);
因此,当我获取其中一篇文章时,我希望title属性是该资源的title属性的任何内容您可以将title属性更改为方法,如下所示:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/partials/home.html',
controller: 'home',
title: function () { return "Corvid"; }
})
.when('/archive', {
templateUrl: "/partials/archive/all.html",
controller: "archive",
title: function () { return "Archive"; }
}).
when('/archive/:id', {
templateUrl: "/partials/archive/one.html",
controller: "article",
title: function (Article) { return Article.get(this.id).title; }
})
.otherwise({
templateUrl: "/partials/errors/404.html",
title: function () { return "Something went wrong!"; }
});
}
]);
然后稍后调用它,并传递注入的文章服务
app.run(['$location', '$rootScope', 'Article',
function($location, $rootScope, Article) {
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
$rootScope.title = current.$$route.title(Article);
});
}
]);
我认为你最好在路上使用resolve。您可以使用它从您的服务中获取文章,同时设置标题。使用解析的示例:
resolve = {
article: ['$route', 'Service', function($route, Service) {
var id = $route.current.params.id;
return Service.get({'id': id}).$promise.then(function(article) {
$route.current.$$route.title = article.id;
return article;
});
}]
}
现在您不必在控制器中获取文章,只需插入文章,同时在路由中设置title属性,这样routechangehandler就可以按预期工作
从API文档中:
resolve-{Object.=}-应注入控制器的可选依赖关系映射。如果这些依赖项中的任何一个是承诺,路由器将在控制器实例化之前等待它们全部被解析或一个被拒绝。如果成功解析所有承诺,则注入已解析承诺的值并触发$routeChangeSuccess事件
请参阅在routeChangeSuccess中插入名为Article的工厂,并获取工厂返回的标题,并为其分配$rootScope.title变量。。。