我使用ng-view包含AngularJS部分视图,我想根据包含的视图更新页面标题和h1标题标记.这些超出了部分视图控制器的范围,因此我无法弄清楚如何将它们绑定到控制器中的数据集.
如果它是ASP.NET MVC你可以使用@ViewBag来做到这一点,但我不知道AngularJS中的等价物.我搜索过共享服务,事件等但仍无法使其正常工作.任何方式来修改我的例子,所以它的工作将非常感激.
我的HTML:
<html data-ng-app="myModule">
<head>
<!-- include js files -->
<title><!-- should changed when ng-view changes --></title>
</head>
<body>
<h1><!-- should changed when ng-view changes --></h1>
<div data-ng-view></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的JavaScript:
var myModule = angular.module('myModule', []);
myModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/test1', {templateUrl: 'test1.html', controller: Test1Ctrl}).
when('/test2', {templateUrl: 'test2.html', controller: Test2Ctrl}).
otherwise({redirectTo: '/test1'});
}]);
function Test1Ctrl($scope, $http) { $scope.header = "Test 1";
/* ^ how can I put this in title and h1 */ }
function Test2Ctrl($scope, $http) { …Run Code Online (Sandbox Code Playgroud) javascript templates partial-views angularjs angular-routing
我正在迁移基于AngularJS的应用程序以使用ui-router而不是内置路由.我把它配置如下所示
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl : 'views/home.html',
data : { pageTitle: 'Home' }
})
.state('about', {
url: '/about',
templateUrl : 'views/about.html',
data : { pageTitle: 'About' }
})
});
Run Code Online (Sandbox Code Playgroud)
如何使用pageTitle变量动态设置页面标题?使用内置路由,我可以做到
$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
$rootScope.pageTitle = $route.current.data.pageTitle;
});
Run Code Online (Sandbox Code Playgroud)
然后在HTML中绑定变量,如下所示
<title ng-bind="$root.pageTitle"></title>
Run Code Online (Sandbox Code Playgroud)
是否有类似的事件,我可以使用ui-router挂钩?我注意到有'onEnter'和'onExit'函数,但它们似乎与每个状态绑定,并且需要我重复代码为每个状态设置$ rootScope变量.