Angular Directive不应用刷新时代码中的更改

时间:2015-03-20 16:59:50

标签: angularjs angularjs-directive

所以我有一个非常基本的指令,我包含在我的基本cshtml文件中,当路由的解析正在加载时显示,然后在加载解析后隐藏。效果很好:

(function () {
    'use strict';

    angular.module('app.directives.resolveLoader', [
        'ngRoute'
    ])
        .directive('resolveLoader', ['$rootScope', '$timeout', '$log', function ($root, $timeout, $log) {
            return {
                replace: true,
                restrict: 'E',
                template: '<div id="resolve-loader">' +
                              '<i class="fa fa-5x fa-spin fa-circle-o-notch emerald-font"></i>' + 
                              '<h3>Loading</h3>' + 
                          '</div>',
                link: function (scope, ele, attrs) {
                    $root.$on('$routeChangeStart', function (event, currentRoute, previousRoute) {
                        $log.info('app.directives.resolveLoader(): Showing resolve-loader');
                        $timeout(function () {
                            ele.removeClass('ng-hide');
                        });
                    });

                    $root.$on('$routeChangeSuccess', function () {
                        $log.info('app.directives.resolveLoader(): Hiding resolve-loader');
                        ele.addClass('ng-hide');
                        $log.info('app.directives.resolveLoader(): ' + ele.hasClass('ng-hide'));
                    })
                }
            }
        }]);
})();

每次我在我的应用程序中找到解决它的新路径时,我会在控制台中看到这一点:

app.directives.resolveLoader(): Showing resolve-loader
app.directives.resolveLoader(): Hiding resolve-loader
app.directives.resolveLoader(): true

如果我刷新页面( F5 Ctrl + F5 ),我会看到同样的事情,但它实际上从未隐藏过该元素我没有看到ng-hide类被应用于DOM中的元素。

为什么会有这样的想法?

1 个答案:

答案 0 :(得分:0)

解决方案是将ele.addClass()包装在$ timeout函数中,如下所示:

                $root.$on('$routeChangeSuccess', function () {
                    $log.info('app.directives.resolveLoader(): Hiding resolve-loader');
                    $timeout(function () {
                        ele.addClass('ng-hide');
                    });
                })