简体   繁体   中英

Why this simple Angular.js example does not work?

I'm reading AngularJS from O'REILLY , and i tried to see how angular works with an example but i can make it functional:

The hello.html :

<html ng-app>
  <head>
    <script src="angular.js"></script>
    <script src="controllers.js"></script>
  </head>
  <body>
    <div ng-controller="HelloController">
      <p>{{ greeting.text }}, World</p>
    </div>
  </body>
</html>

and the logic within the controllers.js :

function HelloController($scope) {
  $scope.greeting = { text: 'Hello' };
}

but when i display the hello.html on the browser, i can see {{ greeting.text }}, Hello .

What is wrong here?

You never defined a controller, you just defined a function that happened to have "controller" in the name.

Try initializing the app properly:

var myApp = angular.module('myApp',[]);

myApp.controller('HelloController', ['$scope', function($scope) {
  $scope.greeting = {text: 'Hello'};
}]);

https://docs.angularjs.org/guide/controller

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