Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

angularjs - Why does ng-controller not work with function this this example?

Im trying to follow along a tutorial but this code doesn't work for me. Can someone expain why and how to solve it? I think its to do with ng-controller but not sure why.

<!doctype html>

<html ng-app>
<head>
<title>AngularJS 2</title>
<script src="angular.min.js"></script>
</head>

<body ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{ author.title + ', ' + author.company }}</p>

<script>
function MyController($scope) {
$scope.author = {
'name' : 'Ray Villa',
'title' : 'Staff Author',
'company' : 'boss`enter code here`.com'
}
}
</script>

</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code would not work with angular 1.3+ because your are defining the controller as a global function.

From AngularJS documentation :

Migrating from 1.2 to 1.3

Controllers

Due to 3f2232b5, $controller will no longer look for controllers on window. The old behavior of looking on window for controllers was originally intended for use in examples, demos, and toy apps. We found that allowing global controller functions encouraged poor practices, so we resolved to disable this behavior by default.

To migrate, register your controllers with modules rather than exposing them as globals Define the controller as follows instead :

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

<body ng-controller="MyController">
  <h1>{{author.name}}</h1>
  <p>{{ author.title + ', ' + author.company }}</p>

  <script>
    angular.module('myApp', []);

    angular.module('myApp').controller('MyController', function ($scope) {
      $scope.author = {
        'name': 'Ray Villa',
        'title': 'Staff Author',
        'company': 'boss`enter code here`.com'
      }
    });
  </script>

</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...