search

Home  >  Q&A  >  body text

angular.js - How to fix the problem that directive in AngularJS does not respond to events triggered when loading

Implement the function of a submenu. If the menu item has submenu, it means it has a submenu. If it has directive, it means the submenu will be expanded when it is loaded. The submenu="expanded" with submenu-for in the submenu indicates which menu item the submenu belongs to, and the value is the directive of the menu item. Such as: id

<a id="m1" submenu="expand">第1项</a> <a id="m2" submenu>第2项</a> <a id="m3" submenu>第3项</a>

<ul submenu-for="m1"><li>第1.1项</li><li>第1.2项</li></ul>
<ul submenu-for="m2"><li>第2.1项</li><li>第2.2项</li></ul>
<ul submenu-for="m3"><li>第3.1项</li><li>第3.2项</li></ul>

CSS only controls attributes such as

through class="submenu-expan" and will not be written. display

The AngularJS code is as follows:

.directive('submenu', ['$rootScope', function($rootScope){
    return {
        restrict: 'A',
        scope: {},
        link: function(scope, element, attrs) {
            scope.$on('submenu-toggle', function(e, id){
                if(id==attrs.id) {
                    element.toggleClass('submenu-expan');
                }
            });

            if(attrs.submenu=='expanded') {
                $rootScope.$broadcast('submenu-toggle', attrs.id);
            }

            element.bind('click', function(){
                $rootScope.$broadcast('submenu-toggle', attrs.id);
            });

        }
    }
}])

.directive('submenuFor', ['$timeout', function($timeout){
    return {
        restrict: 'A',
        scope: {},
        link: function(scope, element, attrs) {
            scope.$on('submenu-toggle', function(e, id){
                if(id==attrs.submenuFor) {
                    element.toggleClass('submenu-expan');
                }
            });
        }
    }
}])

The current problem is that it works normally when responding to the

event, but when responding to the initial settings of click, the ones in submenu="expaned" can act normally, but the ones in submenu have no action. submenuFor

What is the reason? How to solve it?

阿神阿神2858 days ago549

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-15 16:59:56

    Communication between directives requires declaring a controller to minimize broadcast on rotoscope

    reply
    0
  • Cancelreply