Not load a JS file for a specific path - javascript

I have a website by mean-stack.
Normally, all my external references are listed in index.html
I realize that one external JS library (e.g., https://cdnjs.cloudflare.com/troublelibrary.js) I am using has some conflit with a part of my website. So a workaround I am looking for is to NOT load it for a specific path https://www.myexample.com/specific.
Does anyone know how to achieve this in the routing?
Edit 1: (see the full question here)
Actually, the library that has conflit is history.js. My initial code which loads it all the time is as follows. As a result https://localhost:3000/home in a browser is always https://localhost:3000/home (i.e., will not add # because of history.js)
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js"></script>
Then, if I try the following code, as Ben suggests:
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script>
var newScript = document.createElement('script');
newScript.src = 'https://cdn.rawgit.com/devote/HTML5-History-API/master/history.js';
document.head.appendChild(newScript);
console.log(window.location.href)
</script>
I realize that for the first time of loading https://localhost:3000/home will not change. But, if I refresh the browser, it can change to https://localhost:3000/#/home.
So appending the script is not exactly the same as a direct reference, does anyone know why?

I see your problem in a different perspective. You mentioned that you use the history.js to avoid # on the URL. But you do not need history.js to do that. I think you understood your problem in the wrong way. There is an inbuilt Angular functionality to get rid off # paths. Because # is used to keep track of the relative path on any route. If we want we can override that default functionality.
But if you use this approach the server should responsible to redirect the user to index or home page on any application route since Angular handle all the routing in the application.
First you should add
<base href="/" />
in your HTML file.
Then you should enable HTML5 Mode inside Angular application as follows.
$locationProvider.html5Mode(true);
By adding these two attributes you can get rid off the # path and this is the recommended way.
Following is a complete example.
var app = angular.module("app", ["ngRoute"]);
app.controller("MainController", function($scope){
});
//Add route handler
app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
template: '<h1>Home</h1>',
reloadOnSearch: true
})
.when('/about', {
template: '<h1>About</h1>',
reloadOnSearch: true
}).otherwise({
redirectTo: '/'
});
// This will remove hash bang from the routes
$locationProvider.html5Mode(true);
}]);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.js"></script>
<base href="/" />
</head>
<body>
<div>
Home
About
</div>
<div ng-app="app" ng-controller="MainController">
<ng-view></ng-view>
</div>
</body>
</html>
As you can see on the above example when you click on the about link the server responds with not found on /about. This means the # bang is removed.

This is one way to do it:
if(window.location.href !== 'https://url.com/path/to/trouble/page'){
var newScript = document.createElement('script');
newScript.src = 'https://url.com/path/to/script';
document.head.appendChild(newScript);
}
Add this to the <head> of the document. It will not load the trouble script on the page you specify in the if statement. Make sure not to load the trouble script anywhere else on the page as well.

you can do lazy loading of script in angular
<script type="text/javascript" ng-src="{{exUrl1}}"></script>
and somewhere in your code (based on whatever logic you want)
$rootScope.exUrl1 = $sce.trustAsResourceUrl(confserver.example.url);

Related

change ngview from within function

I am using templates to build my app. Basically have one main page, and then I am loading others pages thru it using ng-view. The href links in the index.html work fine. But I also want to be able to change ng-view within js functions as well. How is this done?
I tried to go to the red page using $location.path, but nothing seems to happen besides printing to the console. Before that i tried using $window.location.href(), which did go to the page, but dropped the index.html container, breaking the app.
edit:
As pointed out in Siddhesh's answer comments, it works if not used with $locationProvider.html5Mode(true);. But I would like to keep clean urls. So I'm looking for a way to keep it, IF that's possible.
index.html
<head>
<base href="/testing/onetest/">
<script>
app.controller('masterController',function($location){
setTimeout(change, 3000);
function change() {
console.log("changing in 3 seconds");
$location.path('/red');
}
});
</script>
</head>
<body ng-app="app" ng-controller="masterController">
Main
Red
Green<br>
<div ng-view></div>
</body>
app.js
var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider,$locationProvider) {
$routeProvider
.when("/", {
templateUrl : "home.html",
controller : 'mainController'
})
.when("/red", {
templateUrl : "red.html"
})
.when("/green", {
templateUrl : "green.html"
});
$locationProvider.html5Mode(true);
});
For angular js version less than 1.6
$window.location.href= '#red';
For angular js version 1.6 or more
$window.location.href= '#!red';
Try this and see if it works. This might help you to change the ng-view from function. It worked for me.

After changing pages on small site using ngroute, my jquery toggle doesn't work

Full code:
Plunkr Link
I have been working on a basic AngularJS website and I recently ran into an issue which prevents me from using a jquery toggle after I navigate to a different page. I believe my issue is with the routing since the toggle works if I keep it on my index.html file as well as when I separate page one and put it into codepen. I am unable to find anything too similar around the web that could help me, which is possibly because I have been asking the question incorrectly, however at this point I think I need to ask for help. This may be just a fundamental lack of understanding of ng-route or angular controllers on my end so please bear with me if that's the case/
$(document).ready(function() {
$("#SmMagCld").click(function() {
$("#SMC").toggle(350);
});
});
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<p>PLS JUST LET ME ROUTE TO MY OTHER PAGES AND STILL MAINTAIN FUNCTIONALITY MR ANGULAR... :(</p>
<br>
:(
Page1
Page2
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "main.html"
})
.when("/page1", {
templateUrl: "page1.html"
})
.when("/page2", {
templateUrl: "page2.html"
});
});
app.controller('mainCtrl', function($scope) {
$scope.message = 'welcome hooooooooome';
});
app.controller('page1Ctrl', function($scope) {
$scope.message = 'who is on first';
});
app.controller('page1Ctrl', function($scope) {
$scope.message = 'what is on second';
});
</script>
</body>
</html>
I would also like to say that no errors appear on my localhost when I put it up nor on the plunkr when I run it.
It isn't only the toggle that stops working after routing to a different page but I believe if I can figure out why that isn't working I can apply it to the other similar issues. I created the first site I linked to try and eliminate other possible variables that are causing the issue but if you want to see some other instances of my routes not working, here is another hhttps://plnkr.co/edit/98uEPuLJl8cKGjbrTGsn?p=preview that probably is littered with other mistakes. (not enough reputation to post more than two links so I added an extra h in front of the URL)
I'm fairly new to JavaScript/html, not to mention angularJS, as such any advice about cleaning or improving the code would be much appreciated. Please let me know if any additional information is needed or if I didn't explain my problem clearly.
If it's an angular app your views should be partial (It should not have html or body tags)
Load jquery before angular.
For events you can have ng-click, ng-mouseover, ng-keypress, etc Angularjs html events. And you can write functions on them which has dom manipulation using jquery, inside that page's controller.
onclick doesn't work on images with jquery in document.ready because this event checks only dom tree ready not complete multimedia load.
You can have the onclick binding either by angularjs directives or by binding it inside controller (where it executes on complete load of template).
Here's fixed plunker link : https://plnkr.co/edit/nZJtK1z4FkSIdiQS8Rk8?p=preview

redirect with angularJs to other project

My URL is like : http://localhost:3000/family/#/savings/subscribe/123456
in this page, I want to click on a button to redirect me into other page of another project made with backbone JS
I tried to add the needed URI with href- and ng-href http://localhost:3000/admin#exemption : but it always redirect me to http://localhost:3000/family/#/admin#exemption
angular.module('app', ['ng', 'ngRoute', 'ui.bootstrap', 'angularMoment', 'chart.js'])
.config(fac['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/index', {
templateUrl: '/family/index',
controller: 'IndexCtrl'
})
.when('/family/exemption', {
templateUrl: 'exemption-search-view'
})
when i gave the template of the needed page, I obtain the html view but the URI : http://localhost:3000/family/#/admin#exemption
I'm not sure to understand the question, but if you wanto to avoid angular routing interception, you should add in your anchor target="_self".
<a ng-href="{{vm.logoutUrl}}" target="_self">Bye!</a>
Instead of redirecting with the href (or any variant) try using a function in a controller which redirects you to the new url. Try something like this:
// in your controller
angular.module('app', ['ngRoute'])
.controller('redirectCtrl', function($window, $location){
var vm = this;
vm.wizard = {
anotherurl: "http://example.com",
redirect: fnRedirect
}
return vm.wizard;
function fnRedirect(link){
//this way is useful if you try to redirect to an external URL
$window.location = link;
//this way is useful if you try to redirect to another route inside the same angular project
$location.path(link);
}
});
...and in your html...
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body data-ng-controller="redirectCtrl as rc">
<input type="text" data-ng-model="rc.anotherurl" />
Redirect me
</body>
</html>
If your other project is not part of your angular app, you should redirect to another URL.
Just use .
ng-href is here to append the URL you're passing after the hash in the URL.
The problem in Angular, it redirects you to the same base in his URL, so if you want to change the base (which is /family/#/ in my case), it is like you are going to an external URL from the project so I had just added in my controller :
$window.location.href ='http://localhost:3000/admin#exemption' ;
I don't need any update in my '$routeProvider'

Angular ng-Route doesn't work in a very simple example

I am learning angular.js and found an example on w3c.school
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_routing
But when I try to test it it doesn't work,
I made two .htm files simply containing one word, for example "RED", or "GREEN". As simple as this example is I cannot get it to work. I think that it might be the libraries I am using
<!DOCTYPE html>
<html>
<!-- JavaScript Files -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.js"></script>
<body ng-app="myApp">
<p>Main
</p>
Red
Green
Blue
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl: "test.html"
}).when("/red", {
templateUrl: "red.htm"
}).when("/green", {
templateUrl: "green.htm"
});
});
</script>
</body>
</html>
In this case you are moving towards a page "red.htm" which,... Doesn't exist in your situation! The page is already there in the directory for W3School (http://www.w3schools.com/angular/red.htm for exmaple)
So what you need to do is to create a htm page called red.htm in the same directory and thus navigate to it using routing. If you want to make the same example copy the code of the page I linked and try to run it with both files on the same directory.
From the three files I was using (test.html, red.html, green.html) I finally noticed/understood that you mustn't self-reference the file you are writing the script in.
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/red", {
templateUrl: "red.htm"
}).when("/green", {
templateUrl: "green.htm"
});
});
</script>
Simply by removing the .when method for 'test.html' (which is the exact same file the code is in) the self-referencing stops, and the code is allowed to execute.

angular load template from url and compile inside div

As I'm new to Angular JS I was wondering how could I load an external template and compile it with some data into the targeted div.
For instance I have this template :
<script type="text/ng-template">
<img src="{{Thumb}}" />
<script>
The div that is supposed to contain the template :
<div data-ng-controller=" ... "></div>
The template is located somewhere in a folder /templates/test.php. Is there a build in way of doing the template loading like a directive would do and compile it against some data that would replace the key {{Thumb}} ( and many others of course ) ?
EDIT : What if I use $routes and load a template when I'm in the root of the website ? How could that be achieved ?
Using $templateRequest, you can load a template by it’s URL without having to embed it into your HTML page. If the template is already loaded, it will be taken from the cache.
app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
// Make sure that no bad URLs are fetched. If you have a static string like in this
// example, you might as well omit the $sce call.
var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
$compile($("#my-element").html(template).contents())($scope);
}, function() {
// An error has occurred here
});
});
Be aware that this is the manual way to do it, and whereas in most cases the preferable way would be to define a directive that fetches the template using the templateUrl property.
in Angular there's 2 ways of using template (at least 2 ways that i know about):
the first using an inline template (in the same file) with this syntax:
<script type="text/ng-template">
<img ng-src="{{thumb}}">
</script>
the second one (what you want) is external template:
<img ng-src="{{thumb}}">
so what you need to do is to remove the script part from your template and then use the ng-include in the wanted div like this:
<div ng-include="'templates/test.php'"></div>
need to have double quotes and single quotes to work.
Hope this helps.
Let's say I have this index.html:
<!doctype html> <html lang="en" ng-app="myApp">
<body>
<script src="tpl/ng.menu.tpl" type="text/ng-template"></script>
<mainmenu></mainmenu>
<script src="lib/angular/angular.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
And I have a template file "tpl/ng.menu.tpl" with only these 4 lines:
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
My directives mapping "js/directives.js":
angular.module('myApp',['myApp.directives']);
var myModule = angular.module('myApp.directives', []);
myModule.directive('mainmenu', function() {
return {
restrict:'E',
replace:true,
templateUrl:'tpl/ng.menu.tpl'
}
});

Categories

Resources