首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度子视图/多区域模板、指令和动态模板URL

角度子视图/多区域模板、指令和动态模板URL
EN

Stack Overflow用户
提问于 2013-05-07 04:19:59
回答 2查看 2.1K关注 0票数 2

我正在尝试设置一个带有两个“视图区域”的页面,一个是框架自动处理的标准ng-view,另一个是自定义视图区域,用于使页面的另一部分随着视图的变化而改变。我想我可以/应该用指令来做这件事,但我对Angular还很陌生,很难让它正常工作。

因此,例如,如果我有:

代码语言:javascript
复制
<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来获得当前的“页面”。

代码语言:javascript
复制
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) {
        }
    }

});

有没有更好的方法来做到这一点,或者我可以在这里做些什么来完成我正在尝试的事情?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-07 09:17:09

您可以通过依赖注入将route服务传递到指令中。这也是您能够注入任何其他附加服务的方式。

文档中有更多的信息,但不幸的是没有太多像样的例子:http://docs.angularjs.org/guide/di

注入后,您可以使用$route.currenthttp://docs.angularjs.org/api/ng.$route访问当前路由

代码语言:javascript
复制
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,如果你有大量的路由需要容纳等。

票数 1
EN

Stack Overflow用户

发布于 2013-08-24 16:27:51

我更喜欢使用事件消息而不是路由解析,原因有两个:

  1. 您正在与您的URL建立依赖关系。
  2. 您将只能显示URL

中定义的信息

我建议基于事件的另一种解决方案。首先在导航栏控制器中定义一些事件侦听器:

代码语言:javascript
复制
$scope.$on('logout', function() {
    $scope.setLoggedOutBar();
});
$scope.$on('login', function() {
    $scope.setLoggedInBar();
});
$scope.$on('changeSelectedApp', function() {
    $scope.changeSelectedApp(myContextService.getSelectedApp());
});

然后在您的嵌套视图控制器中,您可以扩展事件:

代码语言:javascript
复制
    $scope.$on('$routeChangeSuccess', function () {
        myContextService.setSelectedApp('main');
        $rootScope.$broadcast('changeSelectedApp');
    });

此解决方案的好处之一是其他组件可以捕获事件并更新其内容。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16406594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档