我正在尝试设置一个带有两个“视图区域”的页面,一个是框架自动处理的标准ng-view,另一个是自定义视图区域,用于使页面的另一部分随着视图的变化而改变。我想我可以/应该用指令来做这件事,但我对Angular还很陌生,很难让它正常工作。
因此,例如,如果我有:
<body>
<div class="fixed-menu">
<nav>this never changes</nav>
<fixed-menu-view></fixed-menu-view> <!-- this need to change with ng-view -->
</div>
<div class="content" ng-view> <!-- this changes with an update to the location/routeProvider -->
</div>
</body>ng-view已经被Angular处理了,但是我需要一个分段的模板来更新页面的另一部分,所以我正在尝试这样做,但不确定如何传入routeProvider来获得当前的“页面”。
directive('fixedMenuView', function () {
// Can't seem to pass in $scope or $routeProvider here
return {
restrict: 'E',
replace: true,
templateUrl: //computed from the current scope or routeprovider url,
link: function (scope, element, attrs) {
}
}
});有没有更好的方法来做到这一点,或者我可以在这里做些什么来完成我正在尝试的事情?
发布于 2013-05-07 09:17:09
您可以通过依赖注入将route服务传递到指令中。这也是您能够注入任何其他附加服务的方式。
文档中有更多的信息,但不幸的是没有太多像样的例子:http://docs.angularjs.org/guide/di
注入后,您可以使用$route.current:http://docs.angularjs.org/api/ng.$route访问当前路由
directive('fixedMenuView', ['$route', function ($route) {
// Can't seem to pass in $scope or $routeProvider here
return {
restrict: 'E',
replace: true,
templateUrl: //computed from the current scope or routeprovider url,
link: function (scope, element, attrs) {
// Do something with $route.current here
}
}
});在你的例子中,我会为指令创建一个‘外壳’模板,里面的开关取决于当前的路由,或者可能是ng-include,如果你有大量的路由需要容纳等。
发布于 2013-08-24 16:27:51
我更喜欢使用事件消息而不是路由解析,原因有两个:
中定义的信息
我建议基于事件的另一种解决方案。首先在导航栏控制器中定义一些事件侦听器:
$scope.$on('logout', function() {
$scope.setLoggedOutBar();
});
$scope.$on('login', function() {
$scope.setLoggedInBar();
});
$scope.$on('changeSelectedApp', function() {
$scope.changeSelectedApp(myContextService.getSelectedApp());
});然后在您的嵌套视图控制器中,您可以扩展事件:
$scope.$on('$routeChangeSuccess', function () {
myContextService.setSelectedApp('main');
$rootScope.$broadcast('changeSelectedApp');
});此解决方案的好处之一是其他组件可以捕获事件并更新其内容。
https://stackoverflow.com/questions/16406594
复制相似问题