angularjs學習筆記-封裝公共模組
阿新 • • 發佈:2019-01-08
1、$rootscope和$scope的區別和作用
$scope是angularJS中的作用域(其實就是儲存資料的地方),很類似javascript的原型鏈 。搜尋的時候,優先找自己的scope,如果沒有找到就沿著作用域鏈向上搜尋,直至到達根作用域rootScope。
$rootScope是由angularJS載入模組的時候自動建立的,每個模組只會有1個rootScope。rootScope建立好會以服務的形式加入到 $injector中。也就是說通過 $injector.get("$ rootScope ");能夠獲取到某個模組的根作用域。更準確的來說,$rootScope是由angularJS的核心模組ng建立的。
scope是html和單個controller之間的橋樑,資料繫結就靠他了。rootscope是各個controller中scope的橋樑。用rootscope定義的值,可以在各個controller中使用。
angular.module('invoice2', ['finance2']) .controller('InvoiceController', ['currencyConverter', function(currencyConverter) { this.qty = 1; this.cost = 2; this.inCurr = 'EUR'; this.currencies = currencyConverter.currencies; this.total = function total(outCurr) { return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr); }; this.pay = function pay() { window.alert("Thanks!"); }; }]);