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

时间:2013-05-06 20:19:59

标签: templates view angularjs routes

我正在尝试设置一个包含两个“视图区域”的页面,一个是框架自动处理的标准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) {
        }
    }

});

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

2 个答案:

答案 0 :(得分:4)

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

  1. 您正在使用您的网址。
  2. 您只能显示网址
  3. 中定义的信息

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

    $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');
        });
    

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

答案 1 :(得分:2)

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

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

注入后,您可以使用$route.currenthttp://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
        }
    }
});

在你的情况下,我会为指令创建一个'shell'模板,其中任何一个开关取决于当前路由,如果你有大量的路由可以容纳等,可能ng-include < / p>

相关问题