Angularjs中的简单依赖注入不起作用

时间:2016-08-06 18:18:34

标签: angularjs dependency-injection

(function () {
    'use strict';

    function myController($scope, $http) {
        var vm = this;
        $scope.text = "Delhi";
    }

    myController.$inject = ["$scope", "$http"];
    angular
       .module("app")
       .controller("myController", myController);
})();

我的Html代码在这里

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="angular.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="myController">
        <p>I am from {{text}}</p>
    </div>
</body>
</html>

但是我的项目没有按预期工作。给出以下错误

https://www.dropbox.com/s/itd5ryar56zqcxn/Screenshot%202016-08-06%2023.46.04.png?dl=0

angular.js:68 Uncaught Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.5/$injector/nomod?p0=app

1 个答案:

答案 0 :(得分:0)

代码存在一些问题,

(i)您需要先定义模块然后注入控制器

(ii)您忘记将空依赖项添加到模块'[]'

(function () {
    "use strict"; 
    angular
       .module("app",[])
       .controller("myController", myController);
    function myController($scope, $http) {
        var vm = this;
        $scope.text = "Delhi";
    }
    myController.$inject = ["$scope", "$http"];    
}());

以下是工作 App