如何重新呈现指令模板和链接功能?

时间:2022-02-08 19:38:37

I am creating a navigation "tree" that basically allows you to navigate to parent views like so

我正在创建一个导航“树”,它基本上允许您导航到父视图,就像这样

Home > Planner > Contacts > john.smith@hotmail.com

主页>规划师>联系人> john.smith@hotmail.com

This list is just a normal <ul> that should get changed each time the view is changed and allow the user to click on any of the above links to navigate. I am using ui-router's $stateChangeStart event to build up my list of links, the problem is that my directive does not "re-build" this list every time the page change.

此列表只是一个普通的

    ,每次更改视图时都应该更改,并允许用户单击上述任何链接进行导航。我正在使用ui-router的$ stateChangeStart事件来构建我的链接列表,问题是我的指令不会在每次页面更改时“重新构建”此列表。

Is there a way to force the directive to re-render every time I change my state?

有没有办法在每次改变状态时强制指令重新渲染?

TreeNav directive

app.directive('treeNav', ['$rootScope', function ($rootScope) {

        return {
            replace: true,
            restrict: 'E',
            template: '<ul>\
                    <li ng-repeat="item in treeNavs">\
                        <a ui-sref="{{ item.state }}">{{ item.name }}</a>\
                        <span> > </span>\
                    </li>\
                   </ul>',
            link: function (scope, elem, attrs) {
                scope.treeNavs = $rootScope.treeNav.reverse();

                scope.$watch('$rootScope.treeNav', function (newVal, oldVal) {
                scope.treeNavs = newVal.reverse();
                });
            }

        }

    }]);

1 个解决方案

#1


2  

I believe you aren't setting up your $watch statement correctly.

我相信你没有正确设置$ watch语句。

You should also be careful with your use of .reverse. reverse() reverses the entries in an array in place, which is probably not what you want to do, since it would modify the array on the $rootScope.

您还应该小心使用.reverse。 reverse()反转数组中的条目,这可能不是你想要做的,因为它会修改$ rootScope上的数组。

You can use splice() to create a new copy and then reverse that:

您可以使用splice()创建一个新副本,然后反转:

scope.treeNavs = $rootScope.treeNavs.splice().reverse();
$rootScope.$watch('treeNav', function(newVal) {
  scope.treeNavs = newVal.splice().reverse();
});

#1


2  

I believe you aren't setting up your $watch statement correctly.

我相信你没有正确设置$ watch语句。

You should also be careful with your use of .reverse. reverse() reverses the entries in an array in place, which is probably not what you want to do, since it would modify the array on the $rootScope.

您还应该小心使用.reverse。 reverse()反转数组中的条目,这可能不是你想要做的,因为它会修改$ rootScope上的数组。

You can use splice() to create a new copy and then reverse that:

您可以使用splice()创建一个新副本,然后反转:

scope.treeNavs = $rootScope.treeNavs.splice().reverse();
$rootScope.$watch('treeNav', function(newVal) {
  scope.treeNavs = newVal.splice().reverse();
});