Dharmik Dharmik - 4 months ago 12x
AngularJS Question

Apply already loaded js in index.html to routed html page in SPA in angularjs

Is it possible to apply js loaded in index.html to new template loaded using route inside ng-view.

<script src="/static/core/js/custom.js"></script>

here is custom.js which i have loaded in my index.html.
And this is my router

.when('/admin/core/user/add/', {
templateUrl : '/static/templates/create_user.html',
controller : 'userController',

so, whenever I am going to load create_user.html in my ng-view of index.html it can't get any effect from custom.js


Here is how you can hook to ngView onload event. Demo first:

angular.module('demo', ['ngRoute'], function($routeProvider) {
    .when('/one', { template: 'One template' })
    .when('/two', { template: 'Two template' })

.run(function($rootScope, $route) {
  $rootScope.__loaded = function() {

// Some global script that does something to content loaded into <ng-view>
function updateView(route) {
  document.querySelector('#ng-view').insertAdjacentHTML('beforeend', `
    <div><small>Hacked from outside: ${route.originalPath}</small></div>
<script src="https://code.angularjs.org/1.5.5/angular.js"></script>
<script src="https://code.angularjs.org/1.5.5/angular-route.js"></script>

<div ng-app="demo">

  <a href="#/one">One</a>  <a href="#/two">Two</a>

    <ng-view id="ng-view" onload="__loaded()"></ng-view>


So the idea is that you specify event handler on the $rootScope (or root controller $scope, doesn't matter). Then from inside of this handler you simply invoke whatever global function you want. That global function can then make whatever DOM manipulations it needs to do with ngView content.