Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  172] [ 1]  / answers: 1 / hits: 32648  / 10 Years ago, tue, august 19, 2014, 12:00:00

Here is my HTML and JS File



HTML file



<!DOCTYPE html>
<html ng-app=>

<head>
<!--Works with latest Stable Build-->
<script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js></script>

<!--Does not work with Latest Beta-->
<!--UNCOMMENT ME! <script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js></script>-->


<script src=script.js></script>
</head>

<body ng-controller=MainController>
<h1>Angular Playground</h1>
{{message}}
<br />Total Length: {{message.length}}
</body>

</html>


JAVASCRIPT FILE



var MainController = function($scope) {
$scope.message = Hello, Michael;
};


If I use the latest stable build, then I get the following result (which is obviously correct):




Angular Playground



Hello, Michael Total Length: 14




However, if I use Beta 18, then I get the following error:




Error: [ng:areq] Argument 'MainController' is not a function, got undefined




and the page returns the following:




Angular Playground #2



{{message}} Total Length: {{message.length}}




Any idea, what could be causing this?


More From » angularjs

 Answers
14

With the latest versions of Angular (>1.3.0), you can't declare a global constructor function and use it with ng-controller.



A quick fix would be to create an angular module and add MainController as a controller.



Here I've wrapped MainController in an IIFE to prevent the function from being added as a global:



(function() {

angular
.module(appName, [])
.controller(MainController, MainController);

MainController.$inject = [$scope];

function MainController($scope) {
$scope.message = Hello, Michael;
};

})();


In your HTML, you'll need to add the name of the angular module to the ng-app directive:



<!DOCTYPE html>
<html ng-app=appName>

<head>
<!--Works with latest Stable Build-->
<script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js></script>

<!--Does not work with Latest Beta-->
<!--UNCOMMENT ME! <script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js></script>-->


<script src=script.js></script>
</head>

<body ng-controller=MainController>
<h1>Angular Playground</h1>
{{message}}
<br />Total Length: {{message.length}}
</body>

</html>

[#69720] Monday, August 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;