Javascript AngularJS重新评估更改$location的指令

Javascript AngularJS重新评估更改$location的指令,javascript,angularjs,Javascript,Angularjs,我正在尝试编写一个nav菜单,根据指定url中的路径隐藏/显示信息 到目前为止,我有以下几点: .directive( "jkSection", function( $routeParams, $location ){ var linker = function( scope, element, attrs){ // Extract the first part of the path. Used to match against the menu l

我正在尝试编写一个nav菜单,根据指定url中的路径隐藏/显示信息

到目前为止,我有以下几点:

.directive( "jkSection", function( $routeParams, $location ){

        var linker = function( scope, element, attrs){
            // Extract the first part of the path.  Used to match against the menu lists
            var currentPath = /^\/?([^/]+)/.exec($location.path())[1];

            // check to see if the path is the same as the attribute
            if( attrs.jkSection.toUpperCase() == currentPath.toUpperCase() )
                element.show();
            else
                element.hide();
        };

        return{
            restrict: "A",
            link: linker
        };
    });
虽然这在页面加载时有效,但当我更改位置时,不会重新应用该指令。我想我需要在$location上添加一个watch,但不确定需要进行何种回调,以便重新评估我的指令

我认为问题的一部分在于,使用my
jk节
指令(在sidebar.html视图中使用)的html不是
ng视图
组件的一部分。但目前,我不想重构我的布局

    <div class="flex-row flex-row--gutter-less flex-hbox main-container">
        <div ng-include="'build/views/sidebar.html'" class="sidebar-wrapper"></div>
        <div class="main-content" ng-view></div>
    </div>


其次,有没有比解析$location.path()更好的方法从路由中提取信息?有没有一种方法可以直接在
$route
对象中指定路由名称/别名/etc?

如果您不想在模板中使用
ng hide/show/If
,请将预期的链接行为放在另一个函数中,并将其作为正在侦听的事件的回调运行

var linker = function( scope, element, attrs){
    function render () {
      // Extract the first part of the path.  Used to match against the menu lists
      var currentPath = /^\/?([^/]+)/.exec($location.path())[1];

      // check to see if the path is the same as the attribute
      if( attrs.jkSection.toUpperCase() == currentPath.toUpperCase() )
          element.show();
      else
          element.hide();
    }

    scope.$on('$locationChangeSuccess', render);

    // Not sure if $locationChangeSuccess triggers on initial load. 
    // If yes, remove this line. 
    render();
};

话虽如此,
ng在模板中隐藏/show/if
可能是更好的方法,只需设置$scope变量,而不是执行
element.show()/hide()

您可以使用
$on
绑定到指令范围内的位置更改事件(即
$locationChangeStart
$locationChangeSuccess
),您还可以传递一个要调用的回调。@miqid-我意识到我可以绑定到事件
$locationChangeSuccess
,但是我不确定在回调函数中放什么。如何让回调函数重新评估模板?你能举个例子吗?我对上下文不太清楚。澄清为什么需要重新评估模板可能有助于提供更优雅的解决方案。无论如何,如果你想重新评估一个模板,这通常是通过使用
$compile
服务并将模板元素重新添加到DOM中来实现的(参见source for exposed one way)。@miqid基本上,我的模板中有一堆链接。我希望一些链接被隐藏,其他的被显示取决于所选的路线。我想我可以使用一个指令来指定显示链接的条件,并让我的directive.link函数计算是否显示元素。但这意味着我需要让指令在$location更改时重新读取模板/重新应用link函数。@EricB。没有理由“重新读取模板/重新应用链接函数”-只需跟踪范围变量,并根据该范围变量在模板中使用
ng hide
/
ng show
/
ng if
。基于任何条件更改location Change事件中的范围变量。工作完美。我是AngularJS新手,我更喜欢使用ng hide/show/if,但是,有几个不同的元素被隐藏,每个元素都有自己必须满足的条件。我在参数中设置了条件,并认为使用指令比在控制器中设置$scope变量更合适。如果我错了,我很想学习如何做得更好。