ThinkTeamwork
ThinkTeamwork

Reputation: 594

How to initiate Controller?

i'm facing a problem when trying to use a different syntax for initiating a controller in my script tag.

Why does this work:

function ListCtrl($scope, Projects) {
    $scope.projects = Projects;
}

and this not:

myProject.controller('ListCtrl', ['$scope', 'Projects', function ($scope, Projects) {
    $scope.projects = Projects;
}]);

Here is the complete plunker http://plnkr.co/edit/Po16QUxmu3M3FqIGqJ3Y?p=preview

Thanks in advance, - Jan

Upvotes: 4

Views: 1115

Answers (1)

Liviu T.
Liviu T.

Reputation: 23664

When using the .controller syntax you also need to change all the routes that used a function reference to use a string reference

Interestingly: using string reference will also work when defining global controller functions, but the current best practice is to use the .controller syntax and avoid global functions.

var myProject = angular.module('project', ['firebase']).
        value('fbURL', 'https://angularjs-projects.firebaseio.com/').
        factory('Projects', function(angularFireCollection, fbURL) {
            return angularFireCollection(fbURL);
        }).
        config(function($routeProvider) {
            $routeProvider.
                    when('/', {controller:'ListCtrl', templateUrl:'list.html'}).
                    otherwise({redirectTo:'/'});
        });

// function ListCtrl($scope, Projects) {
//     $scope.projects = Projects;
// }

// next 3 lines will work
myProject.controller('ListCtrl', ['$scope', 'Projects', function ($scope, Projects) {
   $scope.projects = Projects;
}]);

Upvotes: 3

Related Questions