【问题标题】:AngularJS: Second app in template doesn't work [duplicate]AngularJS:模板中的第二个应用程序不起作用[重复]
【发布时间】:2015-04-25 17:12:39
【问题描述】:

我有两个相同的应用程序(除了应用程序/控制器名称)彼此紧挨着。第一个按预期工作,第二个显然根本没有执行。

我的代码(jsfiddle):

<div ng-app="passwdtool" ng-controller="PasswordController">
Password: <input ng-model="pass" required type="text"><br>
<span>{{ hash }}</span><br>
</div>

<div ng-app="passwdtool2" ng-controller="PasswordController2">
Password: <input ng-model="pass" required type="text"><br>
<span>{{ hash }}</span><br>
</div>
angular.module('passwdtool', [])
.controller('PasswordController', ['$scope', function($scope) {
  $scope.pass = "password";
  $scope.hash = "a hash";
}]);

angular.module('passwdtool2', [])
.controller('PasswordController2', ['$scope', function($scope) {
  $scope.pass = "password";
  $scope.hash = "a hash";
}]);

输出:

密码:[password]
哈希
密码:[]
{{ 哈希}}

发生了什么事?

【问题讨论】:

  • Angular 只启动第一个 ng-app。第二个应该手动启动

标签: javascript html angularjs web


【解决方案1】:

AngularJS 试图找到第一个 ng-app 并启动​​它。 如果您在 html 中定义其他 ng-app,则必须显式启动它们。

功能是:

angular.bootstrap(<elements on which the ng-app will be attached>, <ng-app name>);

在你的情况下应该是这样的:

var domElement = document.getElementById('app2'); //attach app2 id to the element.
angular.bootstrap(domElement, ["passwdtool2"]);

如果您希望在同一页面上有多个 ng-apps,则使用此功能。 看到这个小提琴,我已经修改了你的: https://jsfiddle.net/7bew5q0r/2/

另外,你甚至不需要第二个 ng-app,因为 Angular 无论如何都会忽略它。 所以更新: https://jsfiddle.net/7bew5q0r/3/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2019-05-19
    • 2016-08-18
    相关资源
    最近更新 更多