如何在同一页面中运行两个单独的

如何在同一页面中运行两个单独的

本文介绍了如何在同一页面中运行两个单独的 Angular js 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

Angular 新手.我觉得我遗漏了一些明显的东西:难道我不应该很容易地在同一个 html 页面中运行以分离 AngularJs 应用程序(模块)吗?像这样:

 你好{{name}}!</节><br/><部分 ng-app="MyNameIsApp" ng-controller="MyNameIsController">我的名字是 {{FirstName}} {{LastName}}!</节>

Javascript:

var HelloWorldApp = angular.module('HelloWorldApp', []);HelloWorldApp.controller('HelloWorldController', function($scope) {$scope.name = '世界';});var MyNameIsApp = angular.module('MyNameIsApp', []);MyNameIsApp.controller('MyNameIsController', function($scope) {$scope.FirstName = '约翰';$scope.LastName = '史密斯';});

这只会运行第一个模块,而第二个模块似乎什么也没做.我想这样做,以便我可以为多个页面构建可重用的封装指令,而不必将其模块命名为相同的内容.

实时示例:http://plnkr.co/edit/cE6i3ouKz8SeQeA5h3VJ

我们最终构建了模块的小层次结构,但是我最初的问题可以完成,只需做一点工作(见下文).

解决方案

这是可能的,但需要手动编写一些代码.您需要自己引导 Angular 应用程序.别担心,没那么复杂

  • 不要在 HTML 中添加 ng-app 属性
  • 确保您可以获取保存应用的 DOM 元素
  • 加载 DOM 后,您需要自行启动应用程序:angular.bootstrap( domElement, ['AppName']);

fork of you plunker 哪个有效:http://plnkr.co/edit/c5zWOMoah2jHYhR5Cktp>

New to Angular. I feel like I'm missing something obvious: Shouldn't I easily be able to run to separate AngularJs apps (modules) in the same html page? Something like this:

  <section ng-app="HelloWorldApp" ng-controller="HelloWorldController">
    Hello {{name}}!
  </section>
  <br />
  <section ng-app="MyNameIsApp" ng-controller="MyNameIsController">
    My Name is {{FirstName}} {{LastName}}!
  </section>

Javascript:

var HelloWorldApp = angular.module('HelloWorldApp', []);
HelloWorldApp.controller('HelloWorldController', function($scope) {
  $scope.name = 'World';
});

var MyNameIsApp = angular.module('MyNameIsApp', []);
MyNameIsApp.controller('MyNameIsController', function($scope) {
  $scope.FirstName = 'John';
  $scope.LastName = 'Smith';
});

This only runs the first module, while the second doesn't appear to do anything. I want to do this so that I can build reusable, encapsulated directives for multiple pages that don't have to name their modules the same thing.

Live Example: http://plnkr.co/edit/cE6i3ouKz8SeQeA5h3VJ


We ended up building small hierarchy of modules, however my original question can done, with just a bit of work (see below).

解决方案

It is possible, but it requires a little bit coding by hand. You need to bootstrap the angular apps on your own. Don't worry, it is not that complicated

  • Do not add ng-app attributes in your HTML
  • Make sure you can fetch the DOM elements holding the app
  • When DOM is loaded you need to start the apps on your own: angular.bootstrap( domElement, ['AppName']);

Fork of you plunker which works: http://plnkr.co/edit/c5zWOMoah2jHYhR5Cktp

这篇关于如何在同一页面中运行两个单独的 Angular js 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:39