angularjs:无法将一个模块注入另一个模块

时间:2016-02-08 15:22:23

标签: javascript angularjs

概述:

我有一个包含一组类(模型)的模块。我想把它注入另一个将使用这些类的模块。请让我知道我做错了什么。

错误:

enter image description here

代码:          

<body>
    <div ng-app="TestApp">
        <div ng-controller="Controller"></div>

    </div>

</body>
<script src="https://code.angularjs.org/1.2.8/angular.min.js"></script>
<script>
    // Module with classes, I would like to inject this into the next module
    var classes = angular.module('Models', []);
    classes.factory('Car', function() {
        return {
            honk : function() {
                alert('beep beep!');
            }
        }

    });
    // Main Module.
    var ClientEditApp = angular.module("TestApp", [ "Models" ]);
    // Adding a controller
    ClientEditApp.controller('Controller', [ '$scope', 'Models', function($scope, Models) {
        var c = new Models.Car();
        c.honk();
    } ]);
</script>
</html>

1 个答案:

答案 0 :(得分:3)

1 - 型号是工厂模块。我们没有注入模块。注入&#39; Car&#39;。一个模块可以有很多工厂,因此我们只在需要时注入所需的工厂。
2 - 无法使用实例化工厂。需要直接使用。例如 Car.honk()

更新代码

<script>
    // Module with classes, I would like to inject this into the next module
    var classes = angular.module('Models', []);
    classes.factory('Car', function() {
        return {
            honk : function() {
                alert('beep beep!');
            }
        }

    });
    // Main Module.
    var ClientEditApp = angular.module("TestApp", [ "Models" ]);
    // Adding a controller
    ClientEditApp.controller('Controller', [ '$scope', 'Car', function($scope, Car) {        
        Car.honk();
    } ]);
</script>