patterson patterson
patterson patterson

Reputation: 33

Everytime I add the ng-controller, my app breaks

I've been learning angular.js, and I keep running into the same problem. A simple hello world comes up easy enough:

<body ng-app>
    <h1>Hello, {{name || "World"}}!</h1>
</body>

This comes up fine with the proper scripts in the <head>, but as soon as I add a controller it breaks:

<head>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript">
    angular.module("myApp",[]).controller("MainCtrl",[function($scope) {
        $scope.name = "patterson"
    }]);
</script>
</head>
<body ng-app="myApp" ng-controller="MainCtrl">
    <h1>Hello, {{name || "World"}}!</h1>
</body>

Not only does this not put my name in place of "world", it no longer evaluates the handlebars, instead it leaves the handlebars as raw text. This happens whether it's in the <head> or in a different file. If I remove the reference to the ng-controller, angular works again. Can't figure out what I'm doing wrong...

Here is a jsfiddle of both cases:

https://jsfiddle.net/74t2q2kL/1/

https://jsfiddle.net/74t2q2kL/2/

Thanks for the help!

Upvotes: 1

Views: 89

Answers (4)

Teknotica
Teknotica

Reputation: 1136

If you are using the square brackets format for your Controller, you should pass the scope variable a a string first, like this:

angular.module("myApp",[]).
        controller("MainCtrl",['$scope', function($scope) {
            $scope.name = "Brandon";
        }]);

Upvotes: 1

Michael
Michael

Reputation: 3104

You're function declaration is wrong. There are 2 options. With and without named dependency injection. You mixed them.

Option 1:

angular.module("myApp",[]).controller("MainCtrl",function($scope) {
    $scope.name = "patterson"
});

Option 2:

angular.module("myApp",[]).controller("MainCtrl",['$scope', function($scope) {
    $scope.name = "patterson"
}]);

When you get deeper into Angular this will become more clear.

Upvotes: 0

Dominic Scanlan
Dominic Scanlan

Reputation: 1009

you're not injecting $scope into the controller

angular.module("myApp",[]).controller("MainCtrl",['$scope', function($scope) {
    $scope.name = "patterson"
}]);

Upvotes: 4

Brian Driscoll
Brian Driscoll

Reputation: 19635

Your syntax is incorrect here:

[function($scope) {
        $scope.name = "patterson"
    }]

It should just be:

function($scope) {
        $scope.name = "patterson"
    }

Square brackets [] indicate you are passing an array of things, which you don't want to do in this case.

Upvotes: 6

Related Questions