简体   繁体   English

每次添加ng-controller时,我的应用都会中断

[英]Everytime I add the ng-controller, my app breaks

I've been learning angular.js, and I keep running into the same problem. 我一直在学习angular.js,并且一直遇到相同的问题。 A simple hello world comes up easy enough: 一个简单的hello世界就足够容易了:

<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>使用适当的脚本可以很好地解决这个问题,但是一旦添加控制器,它就会中断:

<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. 这不仅不会将我的名字代替“ world”,也不再评估把手,而是将把手保留为原始文本。 This happens whether it's in the <head> or in a different file. 无论是在<head>还是其他文件中,都会发生这种情况。 If I remove the reference to the ng-controller, angular works again. 如果我删除对ng-controller的引用,角度将再次起作用。 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/1/

https://jsfiddle.net/74t2q2kL/2/ 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 您没有将$scope注入控制器

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: 如果您为Controller使用方括号格式,则应首先将范围变量aa传递给字符串,如下所示:

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

You're function declaration is wrong. 您的函数声明错误。 There are 2 options. 有2个选项。 With and without named dependency injection. 有无命名依赖注入。 You mixed them. 你把它们混合了。

Option 1: 选项1:

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

Option 2: 选项2:

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

When you get deeper into Angular this will become more clear. 当您深入了解Angular时,这将变得更加清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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