我正在使用旧版 MVC 应用程序,我想在其中一个 View 中实现一些 Angular。
在经历了最初让 Angular $compile
新 DOM 的挣扎之后,我留下了一个我似乎无法克服的错误。
它的工作方式(也是我无法改变的)是 jQuery 加载特定的 View /层标记,当它在 DOM 中时,我执行以下操作:
// Compiles the DOM into the Angular application
if ($layer.hasClass('angular-view')) {
angular.injector(['ng']).invoke(function ($rootScope, $compile) {
$compile($layer)($rootScope);
$rootScope.$digest();
});
}
这使我可以在渲染的页面上看到评估值({{2+2}}
),这很棒,但是,当我尝试将 Controller 编译到标记中时,我出现以下错误:
Argument 'MyController' is not a function, got undefined
这是我要注入(inject)到应用程序中的标记:
<div ng-controller="MyController">
<span>{{2+2}} - {{name}}</span>
</div>
以下是我声明应用程序模块的方式:
angular.module('app', [])
.controller('MyController', function ($scope) {
$scope.name = "Terry Nutkins";
});
我正在“主”DOM 中初始化应用程序,如下所示:
<body ng-app>
<!-- Content -->
</body>
(我也尝试过 ng-app="app")
有什么想法吗?
<小时/>我还应该补充一点,当我在调试控制台中查询模块时,我可以看到 Controller 坐在那里,准备就绪。
angular.module('app')._invokeQueue[0][2][0]
"MyController"
最佳答案
我已经找到了问题的原因 - 我希望其他人发现这很有用。
当我注入(inject)并编译 DOM 时,我需要指定要使用哪个注入(inject)器。就我而言,我需要将“app”添加到 angular.injector 调用的数组中
// Compiles the DOM into the Angular application
if ($layer.hasClass('angular-view')) {
angular.injector(['ng', 'app']).invoke(function ($rootScope, $compile) {
$compile($layer)($rootScope);
$rootScope.$digest();
});
}
关于javascript - Angular 使用 Controller 注入(inject)并编译 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422057/