[course] Learn and Understand AngularJS
此篇為各筆記之整理,非原創內容,主要資料來源為 Learn and Understand AngularJS @ Udemy
Model, View, Whatever
在 HTML 中使用 ng-app
和 ng-controller
標註要被綁定的 DOM:
<html lang="en-us" ng-app="myApp">
<!-- ... -->
<body>
<div ng-controller="mainController">
<!-- ... -->
</div>
</body>
</html>
註冊 App 和 Controller:
// 註冊 App
const myApp = angular.module('myApp', []);
// 註冊 Controller
myApp.controller('mainController', function ($scope) {/* ... */});
Services and Dependency Injection
- services @ developer guide
- service components @ API
Dependency Injection
Dependency Injection 指的是「不在函式中建立一個物件,而是把該物件當成參數傳入函式中,達到物件和函式的解耦」。
在 Angular 中,會利用 fn.toString()
的方式將函式轉成字串後進行解析:
const searchPeople = function (firstName, lastName, height, age, occupation) {
return 'John Doe';
};
console.log(searchPeople.toString());
// "function (firstName, lastName, height, age, occupation) {...}"
console.log(angular.injector().annotate(searchPeople));
// ['firstName', 'lastName', 'height', 'age', 'occupation']
在 App 中添加 services
// 第二個參數的 [] 中課業放入要添加的 service
const myApp = angular.module('myApp', ['ngMessages', 'ngResource']);
// 在 controller 中即可透過 dependency injection 取得
myApp.controller('mainController', function ($scope, $resource) {
/* ... */
});