简体   繁体   中英

navigation between templates using directives angular JS

I am trying to navigate between different html templates on click of the button.

I have main html and sub html.

Main.html:

<div id="main"></div>

Sub.html:

<div id="sub"></div>

Index.html:

<my-clicker on-click="ButtonClicked($event)">
            <button class="new_btn">Click Me</button>
        </my-clicker>

Directive Code:

app.directive('myClicker', function () {
        return {
            restrict: 'E',
            scope: {
                onClick: "&"
            },
            link: function($scope, element, attrs) {
                var button = $('.new_btn');
                button.bind("click", $scope.onClick);
                element.append(button);
            }
        };
    });

Controller:

$scope.ButtonClicked = function($event) {
            alert('hai');
        };

Now how do I add my template urls to the button click event. Can anyone please help me out with the sample how we can achieve this scenario.

So according to the comments the usecase here is to swap out one specific part of the DOM when clicking a button.

In this case you don't need a custom directive, you should use ng-include. The ng-include directive is placed on a div (or other dom element) and makes that element load its content from a specified template. You can specify this template as a variable and when you want to swap the content of the div you just change the variable.

Here is an example:

<div id="swappable-content-area" ng-include src="currentTemplate">
    <!-- The content will appear here -->
</div>

<button ng-click="currentTemplate = 'mytemplate.html'">Template 1</button>
<button ng-click="currentTemplate = 'myothertemplate.html'">Template 2</button>

The buttons could of course be a part of the included template.

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