Activating Angular JS on an already loaded non-Angular webpage

徘徊边缘 提交于 2019-12-11 19:30:07

问题


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 replace various blocks on the page. This is from before Angular JS times.

Now, we need to develop a somewhat more complex part on this page, for which we want to use Angular JS, because it would otherwise get quite complex to develop the desired functionality. Without changing the app too much, we want to include Angular just for this small part on the page (a form with some complex rules attached: show, hide, loop, etc...)

My questions are these:

1) How to start Angular JS "on demand"? The page does not have the "ng-app", "ng-controller" or Angular JS loaded initially. I can add these attributes using jQuery when needed and run some code to start it, but this does not seam to work without the page load event.

2) Angular JS should be started though a HTML fragment which the app will include when needed. This fits the old skool way the app works, so we don't want to change this.

3) The existing app uses Prototype JS and jQuery in no conflict mode. Are special steps needed to prevent conflicts when Angular JS enters the picture?

Thanks in advance.


回答1:


you can start angular with

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



回答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>


来源:https://stackoverflow.com/questions/26585110/activating-angular-js-on-an-already-loaded-non-angular-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!