【发布时间】:2015-08-20 22:09:34
【问题描述】:
我的问题是关于从控制器到在该控制器上下文中创建的指令的通信。特别是,我对在这种情况下推荐/最佳方法感兴趣。 我能想到三种不同的可能性:
在指令中使用监视
在这种情况下,指令设置一个监视变量,并在隔离范围内传递一个变量,并对它的变化做出反应:
directive('customDirective', function () {
return {
restrict: 'E',
scope: {
variable: '='
},
link: function (scope, elem, attrs) {
scope.$watch('variable', function (newValue) {
// Do something
});
}
};
});
使用事件
使用第二种解决方案,指令使用作用域上的 $on 函数设置事件处理程序,然后对使用 $broadcast 函数发送的事件做出反应:
directive('customDirective', function () {
return {
restrict: 'E',
link: function (scope, elem, attrs) {
scope.$on('customEvent', function () {
// Do something
});
}
};
});
使用控制对象
我一直在考虑的最后一个选项是让指令使用它打算公开的函数来填充 control 对象。然后,控制器可以在需要时调用此对象上的函数:
directive('customDirective', function () {
return {
restrict: 'E',
scope: {
controlObject: '='
},
link: function (scope, elem, attrs) {
scope.controlObject.fn = function () {
// Do something
};
}
};
});
controller('customController', function () {
this.controlObject = {};
this.performAction = function () {
this.controlObject.fn();
};
});
<custom-directive control-object="ctrl.controlObject"/>
在这种情况下,哪一个被认为是最佳做法?我错过了其他一些选择吗? 谢谢。
【问题讨论】:
-
考虑到您能够列出这 3 个有效选项,我想说您至少对 Angular 有一些了解。这里没有正确的答案。我想说选项 1 和 2 在我看来是最常见的,我个人会根据需要解决的问题使用这两种方法。
标签: javascript angularjs angularjs-directive