简体   繁体   中英

How to show a different directive on click angular JS

Am trying to show the left nav menu, once the menu is clicked from the header bar. I have created two directives, one for header bar and one for menu. But when i clicked on the header bar menu button, the left nav menu should display. but currently it's not working.

this is what i tried:

(function() {
    'use strict';
    angular.module('test.header.module', []);

    angular.module('test.header.module')
        .directive('header',header)
        .directive('menu', menu);

    function header($compile){
        return {
            restrict: 'E',
            template: '<header> <button ng-click="showMenu()"> Test Header </button> </header>'+
                      '<menu ng-if="menuS"></menu>',
            link: function(scope, element, attr){
                scope.showMenu = function(){
                    scope.menuS = true;
                }
            }
        }
    }

    header.$inject = ["$compile"];

    function menu(){
        return{
            restrict:'EA',
            require: '^header',
            template : '<h1 id="test">{{test}}</h1>',
            link : function(scope, element, attr){
                scope.test = "Test Left Nav";
            }
        }
    }

})();

The problem is the require: '^header' - it can't find the 'header' controller. If you remove this your code works. Also, $compile is not needed.

 (function() { 'use strict'; angular.module('test.header.module', []); angular.module('test.header.module') .directive('header',header) .directive('menu', menu) function header(){ return { restrict: 'E', template: '<div> <button ng-click="showMenu()"> Test Header </button> </div>'+ '<menu ng-if="menuS"></menu>', link: function(scope, element, attr){ scope.showMenu = function(){ scope.menuS = true; } } } } function menu(){ return{ restrict:'EA', template : '<h1 id="test">{{test}}</h1>', link : function(scope, element, attr){ scope.test = "Test Left Nav"; } } } })(); 
 <!DOCTYPE html> <html ng-app="test.header.module"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.js" data-semver="1.5.10"></script> <script src="app.js"></script> </head> <body> <header></header> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM