The gap between AngularJS 1.2 and 1.4?

The following code works in Angular 1.2, but breaks in 1.4 with an error Error: [ng: areq] The argument "MyController" is not a function fetched by undefined. The code comes from the book "ng-book" and a live working example can be found here: http://jsbin.com/uHiVOZo/1/edit?html,output .

What changed?

<body>
    <div ng-controller="MyController">
        {{ clock }}
    </div>
    <script type="text/javascript">
        function MyController($scope) {
            $scope.clock = new Date();
            var updateClock = function() {
                $scope.clock = new Date();
            };
            setInterval(
                function() {
                    $scope.$apply(updateClock);
                },
                1000
            );
            updateClock();
        };
    </script>
</body>

      

(Replace https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js with https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0- rc.2 / angular.js in jsbin link)

+3


source to share


2 answers


I didn't know that any version of Angular allowed you to create a controller without first creating a module. Anyway, instantiating the module and registering the controller will fix your problem. jsbin

Add this to your application decalartion in html:

ng-app="app"

      



Change your script:

angular.module('app', []) // this creates a module

function MyController () { ... }

// register controller to module
angular.module('app').controller('MyController', MyController)

      

+2


source


See https://docs.angularjs.org/guide/migration

"Migrating from 1.2 to 1.3 Controllers Because of 3f2232b5, $ controller will no longer look for controllers in the window. The old viewport behavior for controllers was originally intended for use in examples, demos, and toy applications. We found that using functions global controller encourages bad practice, so we decided to disable this behavior by default.

To migrate, register your controllers with modules, rather than expose them as global: "

Before:



function MyController() {
  // ...
}

      

After:

angular.module('myApp', []).controller('MyController', [function() {
  // ...
}]);

      

0


source







All Articles