简体   繁体   中英

Adding ng-controller stops AngularJS

With the below HTML AngularJS is invoked and the webpage prints "5" as the result of {{10/2}} in the "body".

<!DOCTYPE html>
<html ng-app>
<head>
    <title>AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body>
    <h2>hello angular</h2>
    {{ 10/2 }}
</body>
</html>

When I add an ng-controller:

<!DOCTYPE html>
<html ng-app>
<head>
    <title>AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-controller="MainController">
    <h2>hello angular</h2>
    {{ 10/2 }}
</body>
</html>

with the script.js:

var MainController = function($scope){

    $scope.message = "Hello!"
}

AngularJS stops working and the webpage prints {{10/2}} instead of 5. What am I doing wrong here? Thanks.

In script.js , change

var MainController = function($scope){

    $scope.message = "Hello!"
}

to

app.controller('MainController', function($scope) {

  $scope.message = "Hello!"

});

Working Plunker

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