为什么 ng-controller 在这个例子中不起作用? [英] Why does ng-controller not work with function this this example?

查看:29
本文介绍了为什么 ng-controller 在这个例子中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照教程进行操作,但此代码对我不起作用.有人可以解释为什么以及如何解决它吗?我认为这与 ng-controller 有关,但不知道为什么.

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>

推荐答案

您的代码不适用于 angular 1.3+,因为您将控制器定义为全局函数.

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

来自 AngularJS 文档:

从 1.2 迁移到 1.3

控制器

由于 3f2232b5,$controller 将不再在窗口上寻找控制器.在窗口上查看控制器的旧行为最初旨在用于示例、演示和玩具应用程序.我们发现允许全局控制器功能会鼓励不良做法,因此我们决定默认禁用此行为.

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>

这篇关于为什么 ng-controller 在这个例子中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆