下面是index.html文件:
<html ng-app="myApp">
<head>
<title> My Contacts App </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="app.js"></script>
<link rel="shortcut icon" href="favicon.ico"></link>
</head>
<body>
<h1>My contact App </h1>
<div controller="contactCtrl as ctrl">
{{ ctrl.nm }}
</div>
</body>
</html>
app.js如下所示:
var app = angular.module("myApp",[]);
app.controller("contactCtrl",createContacts);
function createContacts()
{
this.nm = "Hey";
console.log("INside controller");
}
问题:当我从源文件所在的同一目录启动http-server并键入 http://127.0.0.1:8080 浏览器仅显示静态html内容时。它显示变量"nm"的值,也不显示控制台中的任何内容.log我处于初学者水平。蒂亚。
这
应该是ng-controller
:
<div ng-controller="contactCtrl as ctrl">
{{ ctrl.nm }}
</div>
下面是如何在 html 中使用 ng-controller
指令的示例:
var app = angular.module("myApp",[]);
app.controller("contactCtrl",createContacts);
function createContacts()
{
this.nm = "Hey";
console.log("INside controller");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myApp">
<head>
<title> My Contacts App </title>
<script src="app.js"></script>
<link rel="shortcut icon" href="favicon.ico"></link>
</head>
<body>
<h1>My contact App </h1>
<div ng-controller="contactCtrl as ctrl">
{{ ctrl.nm }}
</div>
</body>
</html>
pritam 的答案是正确的。为什么不走传统的方式。
var app = angular.module("myApp",[]);
app.controller("contactCtrl",function($scope){
$scope.nm = "Hey";
console.log("Inside controller");
});
在模板中只需使用 {{ nm }}