简体   繁体   中英

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!

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.

you're not injecting $scope into the controller

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM