【问题标题】:Inject module in another module and use controller of injected module在另一个模块中注入模块并使用注入模块的控制器
【发布时间】:2018-12-23 03:22:17
【问题描述】:

我想创建一个模块并注入主模块,并将控制器注入注入模块,但它不起作用

在 index.html 中

<html ng-app="MenuApp">
<head>
</head>
<body>
<div ng-controller="demoCtrl as demo">
<h3>{{demo.hello}</h3>
</body>
</div>
</html

在 app.js 中

(function () {
'use strict';
angular.module('MenuApp', ['data']);
angular.module('data', [])
.controller('demoCtrl', demoCtrl);
demoCtrl.$inject = [];
function demoCtrl() {
var demo = this;
demo.hello = "Hello World";
console.log('Hello World');
}
})();

当我使用 MenuApp 模块声明控制器(demoCtrl)时,它工作正常,但在使用 data 模块声明时不起作用

【问题讨论】:

    标签: javascript angularjs html module


    【解决方案1】:

    如果你提到你给出的例子,你的 html 标签是不正确的,如果不是代码看起来很正常。如果您给出错误,请与我们分享。

    Codepen example of your codes

    以下示例效果很好。

    (function() {
        angular.module('navbar', ['data']);
    
        angular.module('data', [])
            .controller('DataCtrl', function() {
                console.log('Hello Data');
                this.data = 'Hello Data';
            });
    })();
    

    Html 在这里:

    <div ng-app="navbar"> 
        <div ng-controller="DataCtrl as ctrl">  
            {{ ctrl.data }}
        </div>
    </div>
    

    Codepen Example

    【讨论】:

    • 感谢您的回答,其实我的html有点大,所以我在这里缩小并写了,但现在它可以工作了。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多