我正在尝试在页面加载时动态设置页面标题。这是我的代码:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" charset="utf-8" />
<title ng-bind="title"></title>
<style type="text/css">
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
</style>
</head>
<body style="font-family:sans-serif" ng-controller="clicks">
<h1>Hello <span ng-cloak class="ng-cloak">{{ user.name }}</span></h1>
<input type="text" ng-model="user.name" placeholder="Enter a name here" >
<h2>Clicked {{ counter.clicks }} times</h2>
<button ng-click="count()" >Click</button>
<script src="vendor/angular/angular.js"></script>
<script>
angular.module("myApp", ["myApp.controllers"]);
angular.module("myApp")
.run(function($rootScope) {
$rootScope.title = "Angular Learning 1";
});
angular.module("myApp", [])
.controller("clicks", function($scope) {
$scope.user = {
name: "Sithu"
}
$scope.counter = { clicks: 0 };
$scope.count = function() {
$scope.counter.clicks += 1;
}
});
</script>
</body>
</html>
我认为在$rootScope.title
中设置run()
可以更新页面加载中的标题,但事实并非如此。
答案 0 :(得分:1)
它不适合您,因为在使用myApp
声明控制器时覆盖整个angular.module("myApp", [])
模块。这是setter语法,但是你需要getter来检索已经创建的模块。
正确的代码是:
angular.module("myApp")
// Note no [] here --^
.controller("clicks", function($scope) {
$scope.user = {
name: "Sithu"
}
$scope.counter = {
clicks: 0
};
$scope.count = function() {
$scope.counter.clicks += 1;
}
});
你可以改进的另一件事。标题不需要ngBind
,不需要再绑定一个。只需设置document.title
:
.run(function() {
document.title = "Angular Learning 1";
});