Javascript 为什么使用控制器进行指令通信而不是服务
我正在重构一些Angular JS应用程序,我将学习更多关于指令的知识 我已经读过很多次了,如果我们想共享逻辑并使代码干净,那么将控制器绑定到指令是一种很好的做法 将Javascript 为什么使用控制器进行指令通信而不是服务,javascript,angularjs,Javascript,Angularjs,我正在重构一些Angular JS应用程序,我将学习更多关于指令的知识 我已经读过很多次了,如果我们想共享逻辑并使代码干净,那么将控制器绑定到指令是一种很好的做法 将控制器绑定到指令以在多个指令之间共享公共任务非常简单,我理解这种模式的意义。但我的问题是为什么我们需要使用控制器 (示例代码来自) 模式1:使用控制器在指令之间共享逻辑 将控制器绑定到指令: app.directive("superhero", function () { return { restrict: "E",
控制器
绑定到指令
以在多个指令之间共享公共任务非常简单,我理解这种模式的意义。但我的问题是为什么我们需要使用控制器
(示例代码来自)
模式1:使用控制器在指令之间共享逻辑
将控制器
绑定到指令
:
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(myAwesomeFactory) {
return {
require: "superhero",
link: function (scope, element, attrs) {
myAwesomeFactory.addFlight();
}
};
});
与其他指令共享逻辑:
app.directive("flight", function() {
return {
require: "superhero",
link: function (scope, element, attrs, superheroCtrl) {
superheroCtrl.addFlight();
}
};
});
当我想在我的控制器之间共享逻辑时,我会创建一个工厂
,并将其注入控制器。那么为什么不使用相同的模式呢
模式2:使用工厂在指令之间共享逻辑
声明新的工厂
:
app.factory("myAwesomeFactory", function () {
return {
addFlight: function () { /* ... */ }
};
});
使用工厂
进入指令
:
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(myAwesomeFactory) {
return {
require: "superhero",
link: function (scope, element, attrs) {
myAwesomeFactory.addFlight();
}
};
});
我不明白为什么第一种方法比第二种好
额外问题:为什么我们在绑定到指令的控制器中使用这个关键字
非常感谢。我找到了很多关于如何将控制器绑定到指令的教程。但是没有人解释为什么我们需要这样做。我遇到的最大原因是,由于服务是单例的,因此如果有多个指令依赖于同一服务的逻辑,您可能会遇到严重的问题。这就是为什么与视图相关的任何操作都是通过控制器完成的。虽然有时可以在指令中使用服务,但如果可能,最好完全避免这种做法