Angularjs :控制器值未显示在 html 页面中

Angularjs : Controller values not getting displayed in html page

本文关键字:html 显示 控制器 Angularjs      更新时间:2023-09-26

我刚开始学习角度.js .我在app.js文件中编写了一个基本控制器并设置了其属性。我正在尝试在 html 页面中访问这些数据,但徒劳无功。控制器属性值未显示在网页中。下面是代码:

应用程序.js :

(function(){
    var app = angular.module('gemStore',[]);
    var gem = {name: 'Diamond', price: 120, description: 'Hard'};
    app.controller('StoreController', function() {
        this.product = gem;
    });

})();

索引.html

<!DOCTYPE html>
<html ng-app="gemStore">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" ></script>
<script type="text/javascript"  src="js/app.js" ></script>
<p> {{"Hello, Angular!"}}</p>
<div ng-controller="StoreController as store">
<h1>{{store.product.name}}</h1>
<h2>{{store.product.price}}</h2>
<h3>{{store.product.description}}</h3>
</div>
</body>
</html>

请告诉我哪里出错了!!

"控制器作为"语法是在 1.2.0(或大约(中添加的,我认为它不是在 1.0.7 中。尝试使用较新版本的 Angular。如果您坚持使用 1.0.7,则需要使用 $scope .

您的 AngularJS 版本不支持StoreController as store语法。将其更改为StoreController,只需删除store即可。此外,还必须将scope对象inject到控制器中,并改为设置其属性。

这是更新和工作的代码。

var app = angular.module('gemStore', []);
var gem = {
  name: 'Diamond',
  price: 120,
  description: 'Hard'
};
app.controller('StoreController', ['$scope',
  function($scope) {
    $scope.product = gem;
  }
]);
<!DOCTYPE html>
<html ng-app="gemStore">
<head>
  <meta charset="ISO-8859-1">
  <title>Insert title here</title>
</head>
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  <script type="text/javascript" src="js/app.js"></script>
  <p>{{"Hello, Angular!"}}</p>
  <div ng-controller="StoreController">
    <h1>{{product.name}}</h1>
    <h2>{{product.price}}</h2>
    <h3>{{product.description}}</h3>
  </div>
</body>
</html>

在 1.2 版中引入了 angular 中的控制器语法,您使用的是 1.0.7 版。如果将脚本标签中的 angular 版本更新为 1.2 或更高版本,它将正常工作。

<script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js" ></script>

您也可以在以下链接中看到此操作正常工作:http://jsbin.com/tadinesime/2/edit

我希望这有所帮助。

Set

ng-app="gemStore" 

在正文上(或任何包含您的 AngularJS 代码的 HTML 标签中(

这是JSFIDDLE:http://jsfiddle.net/49yrj986/

这是

一门关于 http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/1/section/2/our-first-controller 如果其他人想尝试这些教程的课程