標籤:style blog color 使用 io ar 問題 div cti
在 angular 中我們經常會使用多個 controller 和 指令
他們擁有各自的 $scope , 這就產生了跨$scope調用的問題。
有幾種常見的方法來可以使用.
方法一 : 指令 require
<div directive1="xx"> <div directive2></div> </div> directive("directive1", [function () { return { restrict: "A", link: function () { }, scope: true, controller: ["$scope", function ($scope) { this.alert = function () { $scope.name = "100" } }], name: "directive1Controller" } }]). directive("directive2", [function () { return { restrict: "E", require: "^directive1Controller", //調用父級指令的controller link: function (scope, elem, attrs, directive1Controller) { directive1Controller.alert(); //使用方法 } } }]).
指令通過require,調用其它指令controller方法, 達到通訊
方法二 : service
service("sharing", [function () { this.data = ""; }]). controller("ctrl", ["$scope", "sharing", function ($scope, sharing) { $scope.updateData = function () { sharing.data = "new value"; } }]). directive("directive1", ["sharing", function (sharing) { return { restrict: "A", link: function (scope) { scope.$watch(function () { return sharing.data; }, function () { scope.name = sharing.data; }); } } }]).
模組間如果要通訊最好使用 service 來提供介面 , 那service 和 controller 間可以通過 $watch 來更新$scope.
$watch 有些缺點,記憶體消耗多
方法3 :事件
controller("ctrl", ["$scope", "sharing", "$rootScope", function ($scope, sharing, $rootScope) { $scope.updateData = function () { $rootScope.$broadcast("sharingChange", "new value"); //$emit 是向上冒泡廣播 //$broadcast 是向下廣播 } }]). directive("directive1", ["sharing", function (sharing) { return { restrict: "A", link: function (scope) { scope.$on("sharingChange", function (e, newValue) { scope.name = newValue; }); } } }]).
這是比較官方的做法。
總結 :
子層和父層通訊,多使用繼承的$scope, 指令的 require ,事件廣播
模組間的通訊使用service提供介面會比較容易看的明白, service 和 controller 指令間的通訊,可以用watch,$on或者全域變數(模組內的全域,別用太多既可)
service 介面雖然好, 不過由於指令複用性很高,如果每個操作都開介面的話,很快介面就會很多,所以要確保介面是複用性高的,如果只是為了某次開發為配合某模組而開就不值得了。
$rootScope.$broadcast("Main.myParent.alert", function ($scope) { //某個模組, (通過傳入操作方法,這裡直接寫操作$scope) $scope.name = "keatkeat" }); $scope.$on("Main.myParent.alert", function (e, fn) { //常用指令 fn($scope); //叫用作業方法並把$scope傳入,讓外部的邏輯實現操作$scope });
我們可以把複用性不高的操作,寫在外面,這樣就可以不用寫太多的介面了。
controller 和 指令 通訊方法