我正在重構一些Angular JS應用程序,並且我將更多地瞭解指令。爲什麼使用控制器進行指令通信而不是服務
我讀過很多次將控制器綁定到指令是一個很好的做法,如果我們想共享邏輯並獲得代碼清潔。
將controller
綁定到directive
以共享許多指令之間的常見任務非常簡單,我瞭解此模式的興趣。但我的問題是爲什麼我們需要使用控制器?
(實施例代碼來自this site)
模式1:使用控制器共享指令之間邏輯
綁定一個controller
到directive
:與另一指令
app.directive("superhero", function() {
return {
restrict: "E",
controller: function ($scope) {
$scope.abilities = [];
// [...] additional methods
this.addFlight = function() {
$scope.abilities.push("flight");
};
},
link: function (scope, element) {
element.addClass("button");
element.bind("mouseenter", function() {
console.log(scope.abilities);
});
}
};
});
共享邏輯:
app.directive("flight", function() {
return {
require: "superhero",
link: function (scope, element, attrs, superheroCtrl) {
superheroCtrl.addFlight();
}
};
});
當我想共享我的控制器之間的邏輯時,我創建了一個Factory
,我注入到我的控制器中。那麼爲什麼不使用相同的模式?
模式2:使用工廠指令之間共享邏輯
聲明新factory
:
app.factory("myAwesomeFactory", function() {
return {
addFlight: function() { /* ... */ }
};
});
使用factory
到directive
:
app.directive("flight", function(myAwesomeFactory) {
return {
require: "superhero",
link: function (scope, element, attrs) {
myAwesomeFactory.addFlight();
}
};
});
我無法理解爲什麼第一種方法比第二種方法好。
獎勵問題:爲什麼我們在綁定到指令的控制器中使用this
關鍵字?
非常感謝。我發現了很多關於如何將控制器綁定到指令的教程。但沒有人解釋爲什麼我們需要這樣做。