สิ่งที่ควรรู้
$scope คือ อะไร ?
$scope เป็นตัวกำหนดว่าข้อมูลและฟังก์ชั่นต่างๆ ในภายใต้ขอบเขตของข้อมูลนั้นๆ เช่น ใน controller
ปรับโค้ดจาก Lesson 2: Controller
1. เพิ่ม $scope ลงในพารามิเตอร์ของ controller
(function () {
'use strict'
var app = angular.module('application', []);
app.controller('storeController', function ($scope) {
});
})();
2.เปลี่ยนตัวแปร this เป็น $scope
app.controller('storeController', function ($scope) {
$scope.sushi = {
name: 'Maguro',
price: 200,
description: 'Fat tuna'
};
});
3.เราสามารถเรียกใช้งาน sushi ได้โดยไม่ต้องเรียนผ่าน storeController
<body>
<div class="list-group">
<div class="list-group-item" ng-controller="storeController as store">
<h1>{{sushi.name}}</h1>
<h2>{{sushi.price}} yen<h2>
<p>{{sushi.description}}<p>
</div>
</div>
...
หากต้องการดูตัวอย่างให้เข้าลิงค์นี้ Demo
ข้อควรระวัง
การใช้ตัวแปร $scope มากๆ อาจจะทำให้เกิดปัญหาเรื่องperformance ของระบบ แต่สำหรับมือใหม่ไม่ต้องกังวล
