AngularJS模板标题不呈现

时间:2014-03-11 10:57:13

标签: javascript angularjs

我使用以下代码显示每个AngularJS应用模板的页面标题,但每当我尝试输入无效的URL来测试.otherwise时,我都会收到以下错误:

TypeError: Cannot read property 'title' of undefined
    at http://localhost/app/js/app.js:34:43

以下是使用的app.js,index.html代码:

app.js:

var myApp = angular.module('myApp', ['ngRoute', 'ngSanitize']);
myApp.config(['$routeProvider', function($routeProvider) {

       $routeProvider.when('/home', 
                {     templateUrl: 'templates/index.html', 
                      controller: 'MainController',
                      title: 'Welcome to Home Page'
                });
        $routeProvider.otherwise({
                                    redirectTo: '/home',
                                   title: '404 Not found'

                                 });

}]);


myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

的index.html:

<title ng-bind="title +' - MyAPP Home'"> - MyApp</title>

有人可以通过告诉我我到底做错了什么以及如何解决来帮忙吗?

由于

4 个答案:

答案 0 :(得分:3)

更改此

myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

到此,它将起作用

myApp.run(['$location', '$rootScope', function($location, $rootScope) {
     $rootScope.$on("$routeChangeSuccess", function(event, currentRoute, previousRoute) {
        $rootScope.title = currentRoute.title;
    });
}]);

答案 1 :(得分:2)

试试

 $routeProvider.otherwise({
      redirectTo: '/home',
      title: ''

 });

答案 2 :(得分:1)

我现在正在查看文档,而且我没有看到任何可以这样使用的名称标题字段,您可以阅读:

angular docs

我会让自己更清楚,你不应该只是因为可以在路径对象中添加随机属性。您收到此错误消息是因为每次路由更改时都会触发事件,在这种情况下,当您将网址更改为不匹配/ home的内容时,默认路由会启动,然后查找该随机您在路线对象上设置的属性,它无法找到,因为您还没有为路径/住宅以外的任何其他情况定义它。

此外,您必须使用$$访问的任何属性都是私有的角度,它不应该被轻易使用(如果在下一个版本中他们添加一个名为title的私有属性,你会覆盖它? )

如果要在更改路径时设置页面标题,则应在分配给该路径的控制器中执行此操作。

答案 3 :(得分:1)

routeChange事件需要提供程序中的title属性。

你应该尝试这样的东西来修复。

  $routeProvider
    .when('/home', {
        templateUrl: 'templates/index.html',
        controller: 'MainController',
        title: 'Welcome to my page'
    }).otherwise({
        redirectTo: '/home',
        title: ''
     });