【问题标题】:How to trigger an AngularJS directive every time the view changes?每次视图更改时如何触发 AngularJS 指令?
【发布时间】:2014-02-21 01:39:42
【问题描述】:

我的 index.html 中有这个:

    <div class="content">
        <div data-ng-include="'views/title.html'"></div>
        <div data-ng-view=""></div>
    </div>

    <div data-ng-include="'views/chat.html'"></div>

每当控制器/路由发生变化时,html 就会插入到 data-ng-view 中。

但是,我有一个 Angular 指令,当它看到 chat.html 中的 div 附加了一个类“聊天窗口”时,它会执行一个 Javascript 函数 (callMyJSFunction):

angular.module('myApp').directive('chatWindow', function () {
        return {
            restrict: 'C',
            link: function(scope, element, attrs) {
                element.callMyJSFunction({
                    hostname: 'www.domain.com',
                    data: 'other data'
                });
            }
        }
    });

我想要发生的是,每次视图更改时,都会再次调用此 Javascript 函数。我该怎么做?

请注意,我不想将 chat.html 移动到每个 html 文件中 - 有 20 多种不同的视图!

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以使用从ngView 指令发出的viewContentLoaded 事件。

    在你的指令中,你可以这样做:

    angular.module('myApp').directive('chatWindow', ['$rootScope', function($rootScope) {
        return {
            restrict: 'C',
            link: function(scope, element, attrs) {
                element.callMyJSFunction({
                    hostname: 'www.domain.com',
                    data: 'other data'
                });
    
                $rootScope.$on('$viewContentLoaded', function() {
                    element.callMyJSFunction(...);
                });
            }
        }
    }]);
    

    【讨论】:

      猜你喜欢
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      相关资源
      最近更新 更多