【问题标题】:Activating Angular JS on an already loaded non-Angular webpage在已加载的非 Angular 网页上激活 Angular JS
【发布时间】:2014-10-27 10:07:17
【问题描述】:

我正在寻找一种方法来加载 Angular JS,而不是在页面加载时,而是稍后在需要时。

我的用例是一个预先存在的 Web 应用程序,它使用老式的 jQuery 和 Ajax 来显示和替换页面上的各种块。这是在 Angular JS 时代之前。

现在,我们需要在此页面上开发一个更复杂的部分,我们希望使用 Angular JS,否则开发所需的功能会变得相当复杂。在不过多更改应用程序的情况下,我们希望仅针对页面上的这一小部分包含 Angular(附加了一些复杂规则的表单:显示、隐藏、循环等......)

我的问题是:

1) 如何“按需”启动 Angular JS?该页面最初没有加载“ng-app”、“ng-controller”或 Angular JS。我可以在需要时使用 jQuery 添加这些属性并运行一些代码来启动它,但是如果没有页面加载事件,这将无法正常工作。

2) Angular JS 应该通过应用程序在需要时包含的 HTML 片段启动。这符合该应用程序的旧 skool 工作方式,因此我们不想更改它。

3) 现有应用在无冲突模式下使用 Prototype JS 和 jQuery。 Angular JS进图时是否需要特殊步骤防止冲突?

提前致谢。

【问题讨论】:

    标签: javascript angularjs legacy


    【解决方案1】:

    你可以从角度开始

      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>

      【讨论】:

        猜你喜欢
        • 2018-01-22
        • 2019-08-29
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 2012-11-24
        • 2019-09-01
        • 1970-01-01
        • 2020-07-23
        相关资源
        最近更新 更多