Sunday, February 8, 2015

Change of Angularjs controller definition from 1.2.x to 1.3.x

For Angularjs 1.2.x and older, the global constructor of controller works:
function AppCtrl(){
    console.log("App Controller Msg")
}

But for Angularjs 1.3.x and later, this code will throw the following exception :

 Error: [ng:areq] http://errors.angularjs.org/1.3.12/ng/areq?p0=AppCtrl&p1=not%20a%20function%2C%20got%20undefined
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:6:417
    at Rb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:19:510)
    at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:20:78)
    at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:75:331)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:57:65
    at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:7:408)
    at v (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:56:438)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:51:299)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js:51:316)



The old behavior of looking on 'window' for controllers was originally intended for use in examples, demos, and toy apps. It turns out that allowing global controller functions encouraged poor practices. To migrate from 1.2.x to 1.3.x, you need to register your controllers with modules rather than exposing them as globals:



angular.module('myApp',[]).controller('AppCtrl',[function AppCtrl(){
 console.log("App Controller Msg")
}]);

2 comments:

  1. Hello Rhea, I have been providing AngularJS courses in Chennai for the past 6 months, and at times, I have used your blog as reference for my students in the class. It has been so much useful. Thank you, keep writing more :)

    ReplyDelete
    Replies
    1. Hi Harshita, I am so happy that my blog is useful for your teaching, which entices me to write more.

      Thank you very much!

      Delete