简体   繁体   English

如何在AngularJS中使用Controllers?

[英]How to use Controllers in AngularJS?

I've got a very basic page with a controller, I think it should be pretty obvious what I'm trying to do from the code, but it isn't working. 我有一个带有控制器的非常基本的页面,我认为应该从代码中很明显地看出来,但这是行不通的。

Here is my HTML 这是我的HTML

<!DOCTYPE html>
<html ng-app>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>{{ 800 / 40 }} </h1>
    <h1 ng-controller="MainController">{{message}}</h1>
  </body>
</html>

With the following in script.js 在script.js中使用以下内容

var MainController = function($scope) {
     $scope.message = "Hello";
}); 

The 800 / 40 is displaying 20, so that suggests the Angular script and ng-app is fine, but the value of message isn't being set. 800/40显示20,这表明Angular脚本和ng-app很好,但是未设置message的值。 In the example the ng-controller is in a h1 tag, but I have also tried it in a div which wraps around the h1. 在示例中,ng-controller在h1标记中,但我也在环绕h1的div中进行了尝试。

Any suggestions? 有什么建议么?

Thanks 谢谢

You need to create an angular module 您需要创建一个角度模块

 var myapp = angular.module('myApp', []); myapp.controller('MainController', function($scope){ $scope.message= "Hello"; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <div ng-app="myApp"> <h1 ng-controller="MainController">{{message}}</h1> </div> 

You have to create a Angular module and place that module name for ng-app attribute. 您必须创建一个Angular模块,并为ng-app属性放置该模块名称。

Working solution: https://jsbin.com/nugipinale/1/edit?html,js,output 工作解决方案: https : //jsbin.com/nugipinale/1/edit?html,js,输出

Define angular controller as 将角度控制器定义为

app.controller('MainController', function($scope){
$scope.message = "Hello";
});
   <div ng-app="myApp" ng-controller="MainController">
   <h1>{{ 800 / 40 }} </h1>
  <h1 >{{message}}</h1>
 </div>

<script>
var app = angular.module('myApp', []);
 app.controller('MainController', function($scope) {
  $scope.message = "John";
   });
 </script>

do something like this, 做这样的事情,

Html code HTML代码

 <html>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
 <div ng-app="myApp" ng-controller="MainController">
   <h1>{{ 800 / 40 }} </h1>
  <h1 >{{message}}</h1>
 </div>
 </html>

add this in Script file 在脚本文件中添加

var app = angular.module('myApp', []);
 app.controller('MainController', function($scope) {
  $scope.message = "John";
   });
 </script>

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

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