Angularjs没有模块错误

时间:2016-09-06 17:34:37

标签: javascript angularjs

我不确定我的代码有什么问题,我收到了angular.min.js:17 Uncaught Error: No module: MyApp

的错误

http://jsfiddle.net/9g4nxdar/

(function() {
  angular.module("MyApp")
    .controller('MyCtrl', myController);

  function myController() {
    var vm = this;

    var item = [{
      "name": "James",
      "age": 20
    }, {
      "name": "John",
      "age": 20
    }]


  }
})();

我确实在视图中声明了这一点 <div ng-app="MyApp">

2 个答案:

答案 0 :(得分:2)

问题是您只是获得对模块MyApp的引用。要创建模块MyApp,您需要将数组作为第二个参数传递,如下所示:

app.js

(function(){
    // create the module MyApp
    angular.module('MyApp', []);

})();

controller.js

(function() {

  // get the reference to MyApp and create the controller
  angular.module("MyApp")
    .controller('MyCtrl', myController);

  function myController() {
    var vm = this;

    var item = [{
      "name": "James",
      "age": 20
    }, {
      "name": "John",
      "age": 20
    }]

  }

})();

来自documentation

angular.module(name, [requires], [configFn]);

  

需要 - 如果指定,则创建新模块。如果未指定,则检索模块以进行进一步配置。

答案 1 :(得分:0)

Sonia A - 在你的jsfiddle中,只需将“JavaScript Frameworks&amp; Extensions”更改为“AngularJS 1.4.8”,它就会开始正常工作。

下面是同一个jsfiddle的fork:     http://jsfiddle.net/vcvv04hb/

(function() {
  angular.module("MyApp",[])
    .controller('MyCtrl', myController);

  function myController() {
    var vm = this;
    vm.items =  [{
      "name": "James",
      "age": 20
    }, {
      "name": "John",
      "age": 20
    }];
  }
})();
<div ng-app="MyApp">
  <div ng-controller="MyCtrl as vm">
    <ul>
      <li ng-click="vm.viewDetail = true" ng-repeat="item in vm.items">{{item.name}}
        <small ng-show="vm.viewDetail">{{vm.item.age}}</small>
      </li>
    </ul>
  </div>
</div>