Skip to content Skip to sidebar Skip to footer

Activating Angular JS On An Already Loaded Non-Angular Webpage

I'm looking for a way to load Angular JS not on page load, but later on, when needed. My use case is a pre-existing web app, that uses old-school jQuery and Ajax to show and replac

Solution 1:

you can start angular with

  angular.bootstrap(document, ['myApp']);
  $('html').addClass('ng-app: myApp');

Solution 2:

    <html>
    	<head>
    		<script>
    			function injectAngular(e){
    				e.style.display = "none";
    				document.body.setAttribute("ng-app", "MyApp");
    				document.body.setAttribute("ng-controller", "MyCtrl");
    				document.body.setAttribute("ng-init", "name = 'test'");
    				
    				var input = document.createElement('input');
    				input.setAttribute("ng-model", "name");
    				
    				document.body.append(input);
    				
    				var span = document.createElement('span');
    				span.innerHTML = " test <br> <span ng-repeat='x in splitWord() track by $index'> {{x}} <br></span>";
    				
    				document.body.append(span);
    				
    				var script = document.createElement('script');
    				script.onload = function(){
    					var app = angular.module("MyApp", []);
    					app.controller("MyCtrl", function($scope, $http) {
    						$scope.splitWord = function(){
    							return $scope.name.split(/.{0}/);
    						};
    					});
    				};
    				
    				script.src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js";
    				document.head.append(script);
    			}
    		</script>
    	</head>
    	<body>
    		<button onclick="injectAngular(this)">Inject angular</button>
    	</body>
    </html>

Post a Comment for "Activating Angular JS On An Already Loaded Non-Angular Webpage"