USheokand USheokand - 4 months ago 28
AngularJS Question

Not able to include 2 controller.js files on single html page. Getting Error- Argument {mycontroller} is not a function, got undefined

I am new to angular, and stuck with nested angular controllers. I have kept all the controllers in separate .js files.

The main controller on my problem (html)page must nest another controller 'UploadController' to upload images.

I don't want to keep the main controller and UploadController in same file because the Uploadcontroller will be used at other pages also.

// app.js

(function () {
'use strict';
angular.module('myApp', []);

})();


// MainController.js

(function () {
'use strict';

var app = angular.module('myApp', []);
app.controller('MainController', ['$scope', '$http', function ($scope,$http)
{
// my code
}]);

}());


// UploadController.js

(function () {
'use strict';

var app = angular.module('myApp', ["ngMessages"]);
app.controller('EditController', ['$scope', '$http', function ($scope,$http)
{

// Code

}]);

}());


// page.html

<title>
<script src="/cdn/scripts/angular/app.js"></script>
<script src="/cdn/scripts/angular/controller/maincontroller.js"></script>
<script src="/cdn/scripts/angular/controller/uploadcontroller.js"></script>

</title

<body>

<div ng-app="myApp">
<div ng-controller="MainController">
<div ng-controller="UploadController">

</div>
</div>
</div>
</body>


This is the error I am getting while running the Code.

Argument 'MainController' is not a function, got undefined

Thanks.

Answer

Try this,

(function() {
    'use strict';
    angular.module('myApp', []);
})();
(function() {
    'use strict';
    angular.module('myApp').controller('MainController', ['$scope', '$http', function($scope, $http) {
        // my code      
        $scope.name = "main controller";
    }]);
}());
(function() {
    'use strict';
    angular.module('myApp').controller('EditController', ['$scope', '$http', function($scope, $http) {
        // Code
        $scope.name = "edit controller";
    }]);
}());
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js@1.4.x"></script>
    
<body ng-app="myApp" >
    <div ng-controller="MainController">
    <p>Hello {{name}}!</p>
    </div>
     <div ng-controller="EditController">
    <p>Hello {{name}}!</p>
    </div>
    
  </body>