简体   繁体   中英

Undefined Controller AngularJS

My template is loading but I get an error that the controller is undefined. The controller does exist in my sources exactly at the location defined. What is wrong with this code?

Error: [ng:areq] http://errors.angularjs.org/1.2.14/ng/areq?p0=ItemsController&p1=not%20aNaNunction%2C%20got%20undefined
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js:6:450
    at xb 

This is my html:

<div ng-app="myApp">
  <ul ng-controller="ItemsController" class="nav">
    <input type="text" value="ItemName" ng-model="newItemName" placeholder="name of new item...">
    <button ng-click="addItem()">Add Me</button>
    <li ng-repeat="item in items.data" id="item{{item.id}}">
      <a href="#">{{item.title}}</a> 
      <a ng-click="deleteItem($index)" class="fa fa-trash-o"></a>
    </li>
  </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-route.js"></script>
<script type="text/javascript" src="js/te.js"></script>

'use strict';
var myApp = angular.module("myApp", []);
myApp.factory("items ", function() {
  var items = {};
  items.data = [];
  return items;
});
myApp.controller("ItemsController", function ItemsController($scope, items) {
  $scope.items = items;
  $scope.deleteItem = function(index) {
    items.data.splice(index, 1);
  }
  $scope.addItem = function(index) {
    items.data.push({
      id: $scope.items.data.length + 1,
      title: $scope.newItemName
    });
  }
});

The Only Problem I see in your code is in following line:

myApp.factory("items ", function() {

space in the factory name "items " and you are injecting in your controller as items.

Here is the working PLNKR of your code, proof its working fine.

Happy Helping!

I have faced this problem many a times and usually this is caused when you have not included your js in the template.

If its not the case, then if you could share your some part of code, then only anybody will be able to answer it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM