Uncaught Error: [$injector:modulerr] when using ng-repeat

时间:2016-04-21 22:27:40

标签: javascript angularjs

angular.module('app',[])
  .controller('myCtrl',function() {
    this.items = m;
});

var m = {
    "India": "4",
    "England": "2",
    "Brazil": "3",
    "UK": "1",
    "USA": "3",
    "Syria": "2"
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body>

  <h3>FIFA Mactch Summary:</h3>
  <div ng-app='app' ng-controller="myCtrl">
      <ul>
          <li ng-repeat="(country,goals) in items">{{country}}: {{goals}}</li>
      </ul>
  </div>

</body>

Above is my code. When I run it, got Uncaught Error [$injector:modulerr] error. I can not figure out why get this error. Anyone could help me? Really appreciate that.

1 个答案:

答案 0 :(得分:1)

In order for you to access Angular properties in the DOM, you need to establish a scope and inject $scope as a dependency in your controller, which you do by placing it in the function argument. Then you need to assign your items to something on the scope object for it to be accessed in the DOM. For it to work, it should look something like this. Additionally, I'd avoid something like the m object floating outside the controller. If your only using something in one controller, I'd say it's best to keep the information inside that controller.

angular.module('app',[])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.items = {
    "India": "4",
    "England": "2",
    "Brazil": "3",
    "UK": "1",
    "USA": "3",
    "Syria": "2"
    };
}]);
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body>

  <h3>FIFA Mactch Summary:</h3>
  <div ng-app='app' ng-controller="myCtrl">
      <ul>
          <li ng-repeat="(country,goals) in items">{{country}}: {{goals}}</li>
      </ul>
  </div>

</body>