Specify javascript code to certain html templates

Currently im working on an app that has many hrefs within html strings, which leads to using the InAppBrowser plugin. No issue so far, as long as you only use it for a single page app. But the moment you have many more pages that use certain javascript to make their functions work. It becomes a big problem, for example this piece of javascript:

    $scope.$on("$ionicView.enter", function () {
        console.log("clickable");

        document.onclick = function (e) {
            e = e || window.event;
            var element = e.target || e.srcElement;
            console.log(e);

            console.log(element);
            if (element.tagName == 'A') {
                window.open(element.href, "_system", "location=yes");
                return false; // prevent default action and stop event propagation
            }
        };
    });

This script is used to make all hrefs within a page work, so you can open a browser with no problem. But once you inject this piece of Javascript, it will be available to the whole app. My assumption is that the issue is because of the whole app is running in 1 index.html file with templates. Current solution to this is to apply this:

    $scope.$on("$ionicView.leave", function () {
        console.log("not clickable");
        document.onclick = function (e) {
            e = e || window.event;
            var element = e.target || e.srcElement;

            if (element.tagName == 'A') {
            }
        };
    });

This piece of Javascript will be called when the view is no longer active, which will overwrite the tapping function on a href.

I hope there is a better solution for this because currently it is not waterproof at all.