The Bndr
The Bndr

Reputation: 13394

Error while defining an angularjs controller

I have an view (insight index.html) like that:

<body ng-app="mainApp" ng-controller="MainCtrl">
[...]
    <div>{{status}} </div>
</body>

I start the App onDeviceReady:

angular.element(document).ready(function() {
    angular.bootstrap(document);
});

I have this module:

var mainAppModul = angular.module('mainApp', ['ngRoute'])
         .config(function ($routeProvider, $compileProvider) {

       $routeProvider
         .when('/', {
         controller: MainCtrl,
         template: '<h1> Main View {{ status }} </h1>'        
         });
       $compileProvider.aHrefSanitizationWhitelist (/^\s*(https?|ftp|mailto|file|tel):/);
    });

As far as I know, there are different ways to define a controller. One way is like that:

mainAppModul.controller('MainCtrl',['$scope', function ($scope)
 {
    $scope.status = "It works!";
}]);

The other one is like this:

function MainCtrl ($scope) 
{
   $scope.status = "It works!";
}

While the 1st Version results in [ng:areq] Argument 'MainCtrl ' is not a function, got undefined, the 2nd Version works fine.

Is there something I misunderstood in general?

Upvotes: 0

Views: 223

Answers (1)

m.e.conroy
m.e.conroy

Reputation: 3538

ngRoute works in combination with ngView You won't need to specify the ng-controller in your templates, ngRoute takes care of that for you. When you have this:

var mainAppModul = angular.module('mainApp', ['ngRoute'])
.config(function ($routeProvider, $compileProvider) {
    $routeProvider
        .when('/', {
            // controller: MainCtrl, // EDIT: needs to be a string of the controller name
            controller: 'MainCtrl',
            template: '<h1> Main View {{ status }} </h1>'
        });
});

All you need is this:

<html ng-app="myApp">
    <body>
        <ng-view></ngview>
    </body>
</html>

ngRoute will put the template of the specified route into ng-view and use the associated controller.

Note: ngRoute does not come with angular.js, you'll need the angular-route.js included as well.

Upvotes: 1

Related Questions