Angular js [02] - 控制器(ngController)

1.4 Our First Controller 210 PTS

In order to add some behavior to our application, we need a controller. Add a controller named StoreController to our gemStore application.

 

1.首先先由原先的app建立一個控制器

(function(){
var gem = { name: 'Azurite', price: 2.95 };
var app = angular.module('gemStore', []);
app.controller('StoreController', function(){ });
})();

2.在HTML中加入此控制器,並在此把store作為StoreController

<!DOCTYPE html>
<html ng-app="gemStore">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="StoreController as store">
<div class="product row">
<h3>
<em class="pull-right"></em>
</h3>
</div>
</body>
</html>

3.把物件加入
(function(){
var gem = { name: 'Azurite', price: 2.95 };
var app = angular.module('gemStore', []);
app.controller('StoreController', function(){ this.product = gem;});
})();

4.執行顯示變數出來

<!DOCTYPE html>
<html ng-app="gemStore">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="StoreController as store">
<div class="product row">
<h3>
{{store.product.name}}
<em class="pull-right"> {{store.product.price}}</em>
</h3>
</div>
</body>
</html>