AngularJS:当控制器X处于活动状态时,如何允许/启用指令?

时间:2014-08-09 01:04:15

标签: angularjs directive

或换句话说:当控制器X不再处于活动状态时,如何停止/销毁指令?

我需要这个功能,以便我可以阻止"运行"当路由到不同的页面时。一直在研究你的文档,但无法找到这个简单问题的答案。

以下是该指令的HTML / Jade代码:

doctype html
html(data-ng-app="videomailApp")
    body
        main(data-ng-view, data-ng-cloak)
            h2 Changelog
            ul#changelog(data-ng-highlightVersion)
                each version, i in versions
                    li(id=version.number)
                        h3
                            a(href="#" + version.number) Version #{version.number}
                            if i === 0
                                | [current]
                        | !{version.changelog}

然后我的自定义浏览器AngularJS指令突出显示当前选择的版本如下:

module.exports = function($location) {
    return function($scope, $element) {

        var versions   = $element.children(),
            onClass    = 'current',
            versionMap = {},

            $currentVersion,
            $version,
            i

        for (i = 0; i < versions.length; i++) {
            $version = angular.element(versions[i])
            versionMap[$version.attr('id')] = $version
        }

        /*
            Problems to solve:
            - how can i enable this directive only when on that page?
            - the event below is not fired on page load
            - if nothing works, consider moving all that to the controller which is much easier
        */

        $scope.$on('$routeChangeStart', function() {
            var id = $location.hash()

            var $version = versionMap[id]

            if ($version) {
                if ($currentVersion)
                    $currentVersion.removeClass(onClass)

                $currentVersion = $version
                $currentVersion.addClass(onClass)
            }
        })
    } }

我使用此

在main.js中加载指令
app.directive('highlightVersion', ['$location', require('./directives/highlightVersion')])

就像我提到的,无论该页面是否处于活动状态,或者用户是否已将路由更改为其他页面,看起来该指令始终在运行。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您只需使用ng-if属性即可删除/创建dom。

https://docs.angularjs.org/api/ng/directive/ngIf