29

I am new to Angular JS and I am using the 1.6 version of it.

I have this apptest.js script:

var myApp = angular.module("myApp", []);

(function(){
    "use strict";
    myApp.controller("productController", function($scope, $http)

    {
        $http.get('data/data.json').then(function(prd)
        {
            $scope.prd = prd.data;
        });
    });
});

And here my data/data.json data:

[
  {
    "id":"1",
    "title":"20 Foot Equipment Trailer",
    "description":"2013 rainbow trailer 20 feet x 82 inch deck area, two 5,000 lb axels, electric brakes, two pull out ramps, break away box, spare tire.",
    "price":6000,
    "posted":"2015-10-24",
    "contact": {
      "name":"John Doe",
      "phone":"(555) 555-5555",
      "email":"[email protected]"
    },
    "categories":[
      "Vehicles",
      "Parts and Accessories"
    ],
    "image": "http://www.louisianasportsman.com/classifieds/pics/p1358549934434943.jpg",
    "views":213
  }
]

Now here is my html page where I specified the ng-app and ng-controller:

<body ng-app="myApp" ng-controller="productController">
<div class="row">
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Add <span class="sr-only">(current)</span></a></li>
          </ul>
          <form class="navbar-form navbar-left">
            <div class="form-group">
              <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>

    <div class="col-sm-4" ng-repeat="product in prd">
        <div class="panel panel-primary">
            <div class="panel-heading">{{product.title}}</div>
            <div class="panel-body">
                <img ng-src="{{product.image}}">
                {{product.price | currency}}
                {{product.description}}
            </div>
            <div class="panel-footer">a</div>
        </div>
    </div>
</div>

<script src="angular/angular.js"></script>
<script src="scripts/appTest.js"></script>
</body>

I am still getting the following error which is new for me:

angular.js:14239 Error: [$controller:ctrlreg] The controller with the name 'productController' is not registered. http://errors.angularjs.org/1.6.0-rc.0/$controller/ctrlreg?p0=productController

Any help is appreciated.

4
  • 8
    Your IIFE isn't being invoked, you should change it to (function () {...})(); you must add the () to the closure function so that it will be called and then your controller will be registered.
    – lenilsondc
    Nov 21, 2016 at 12:57
  • Can you explain why we use IIFE now in angular ? Please, it is blur to me.
    – alim1990
    Nov 21, 2016 at 13:02
  • 2
    It's a javascript issue actually, IIFE means Immediatly Invoked Function Expression, its purpose is mostly for code isolation from the root window object, once you use an IIFE all declarations are restricted to that scope. It's basicaly all about scope isolation. Check this wikipedia article about it en.wikipedia.org/wiki/Immediately-invoked_function_expression
    – lenilsondc
    Nov 21, 2016 at 13:05
  • 1
    Thanks sir I appreciate your help.
    – alim1990
    Nov 21, 2016 at 13:24

8 Answers 8

24

Its because of your Immediately Invoked Function Expression. you have to change it like below :

var myApp = angular.module("myApp", []);

(function(app){
  "use strict";
  app.controller("productController", function($scope, $http){
    $http.get('data/data.json').then(function(prd){
      $scope.prd = prd.data;
    });
  });
})(myApp);
3
  • context is myApp not app
    – Madasu K
    Nov 21, 2016 at 13:01
  • yes i think you are misspell App instead of myApp in parameter isn't it ? Jun 7, 2017 at 10:49
  • 6
    no, i didn't mis spell it. I am passing myApp as argument so i can use any variable alias inside self invoking function. Jun 8, 2017 at 4:53
22

Just import the file in index.html,

<script src=".../productController.js"></script>
2
  • 1
    Please do not post identical answers to different questions -> stackoverflow.com/questions/41460755/… Besides that, the whole point by using a generator and grunt is to get rid of manual insertion of scripts to index.html Mar 21, 2017 at 21:26
  • thanks for guidance...i used gulp to get rid of manual insertion
    – Saeed
    Mar 24, 2017 at 10:31
3

In my case, it was missing reference in index page as well as my controller name was startupController (notice lower case s) and I was trying to register it with StartupController (upper case s)

0
2

In my case, with this same error, I failed to identify the app module in the ng-app directive like this:

<div class="row" ng-app>

In some circumstances I've seen where ng-app is by itself but I was forced to identify the app like:

<div class="row" ng-app="myApp">

2

In My case, I just copied a piece of code from an example, and it contained another ng-app and ng-controller in one of its <DIV>. The message was initially confusing, as the required controller had the name Ctrl

enter image description here

If you are reading this, check the name of the controller not found on your web browser console. Mine was Ctrl

So, I realized that my structure had another controller named like this one:

Bad Code

<html ng-app="sampleApp">
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body ng-controller="SampleCtrl">
<h1>{{message}}</h1>

<!-- SEE THIS TABLE HAS A CONTROLLER WITH A VERY UNDEFINED NAME, SO IT MAKES IT DIFFICULT TO TRACK -->

 <table ng-app="app" ng-controller="Ctrl" >
  <td>
	 <div>Select an image file: <input type="file" id="fileInput" /></div>
   <div class="cropArea">
	   <ui-cropper image="myImage" area-type="rectangle" aspect-ratio="1.7" result-image="myCroppedImage" result-image-size='{w: 340,h: 200}' init-max-area="true">
     </ui-cropper>
 	 </div>
  </td>
  <td>
 	 <div>Cropped Image:</div>
	 <div><img ng-src="{{myCroppedImage}}" /></div>
  </td>
 </table>
</body>

<script>

		var myApp = angular.module("sampleApp", []);
		
		myApp.controller("SampleCtrl", function ($scope) {

			$scope.message = "It Works!";
			
		});
  
</script>

SOLUTION

After removing the controller and app definition not initially desired, it worked like a charm.

<html ng-app="sampleApp">
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body ng-controller="SampleCtrl">
<h1>{{message}}</h1>

<!-- SEE THE NOW DOES NOT HAVE A CONTROLLER, THE CONTROLLER WILL BE MY DEFAULT APP CONTROLLER SampleCtrl -->

 <table>
  <td>
	 <div>Select an image file: <input type="file" id="fileInput" /></div>
   <div class="cropArea">
	   <ui-cropper image="myImage" area-type="rectangle" aspect-ratio="1.7" result-image="myCroppedImage" result-image-size='{w: 340,h: 200}' init-max-area="true">
     </ui-cropper>
 	 </div>
  </td>
  <td>
 	 <div>Cropped Image:</div>
	 <div><img ng-src="{{myCroppedImage}}" /></div>
  </td>
 </table>
</body>

<script>

		var myApp = angular.module("sampleApp", []);
		
		myApp.controller("SampleCtrl", function ($scope) {

			$scope.message = "It Works!";
			
		});

	  
</script>

1

I have the same problem. I solved the problem by puting the js code in the main js. my html is a layer on the main html my original html and js are following :

<div style="background: #f5f5f5;" ng-app='myapp'  ng-controller="cIdentityCtrl as ctrl">
    <form class="padding-md" name="staffForm" ng-submit="submit()">
        <div class="row popup" style="padding-bottom: 10px;" ng-repeat="item in sfList">
            <label style="width: 130px;text-align: right;"> {{item.branchName}}:</label>
            <input type="text" style="width: 175px;display: inline-block;" class="form-control" ng-model="item.PERCENT"
                   placeholder="股份比例">%
        </div>
        <div class="clearfix"></div>
        <div class="height50"></div>
        <div class="text-center iframe-layer-btn">
            <button type="submit" class="btn btn-success" ng-disabled="staffForm.$invalid">保存</button>
            <button type="button" class="btn btn-default" ng-click="close()">关闭</button>
        </div>
    </form>
</div>

<script>
var myapp= angular.module('myapp',[]);
    (function(myapp){
        "use strict";
        myapp.service('layerService', layerService)
        .factory('instance', instance);
        myapp.controller('cIdentityCtrl', function($scope, instance, layerService) {
            console.log(instance.storeList)
            $scope.sfList = angular.copy(instance.storeList);
            $scope.submit = function(){
                for(var i=0;i<$scope.sfList.length;i++){
                    if($scope.sfList[i].PERCENT!=null && $scope.sfList[i].PERCENT!=''){
                        if(!/^(((\d|[1-9]\d)(\.\d{1,2})?)|100|100.0|100.00)$/.test($scope.sfList[i].PERCENT)){
                            massage.error($scope.sfList[i].branchName+'门店设置有误:[0,100]保留二位小数');
                            return false;
                        }
                    }
                }
                instance.fnsf($scope.sfList);
                layerService.close(instance.layero1);
            }

            $scope.close=function(){
                layerService.close(instance.layero1);
            }
        });

    })(myapp);
</script>


this html and js opened by ng-include ,but can not find the controller . and I put the js in the parent html`s js file and it worked well.

1

I had same issue and found the reason as... The app module in the ng-app directive was defined/used at body-tag level like this

<body ng-app="intervalAngularExample">

and the $controller definition in productionController.js was imported in the html file at header level, certainly that should not work.

<head>
<script src=".../productController.js"></script>
</head>
<body ng-app="intervalAngularExample">
</body>

import should be then inside the body tag.

0

This error occurs when the $controller() service is called with a string that does not match any of the registered controllers. The controller service may have been invoked directly, or indirectly, for example through the ngController directive, or inside a component / directive / route definition (when using a string for the controller property). Third-party modules can also instantiate controllers with the $controller() service

Causes for this error can be:

1- Your reference to the controller has a typo. For example, in the ngController directive attribute, in a component definition's controller property, or in the call to $controller().

2- You have not registered the controller (neither via Module.controller nor $controllerProvider.register().

3- You have a typo in the registered controller name.

ref: https://docs.angularjs.org/error/$controller/ctrlreg?p0=GreetingController

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.