[英]Directive communication - sharing a reference to an inner HTML element
I want to find a way to do clean communication between my two sibling directives. 我想找到一种在两个兄弟指令之间进行干净通信的方法。 I want to implement "insertAtCaret" functionality for a textarea in one directive, to be called from another. 我想在一个指令中为一个文本区域实现“ insertAtCaret”功能,该指令可以从另一个指令中调用。
<text-holder ng-model='model.text' />
<text-inserter>
<a ng-click='insert("hello")'>Hello</a>
</text-inserter>
text-holder
turns into something like this: text-holder
变成这样的事情:
<div class='my-class'>
<h3>Enter some text:</h3>
<textarea ng-model='ngModel'></textarea>
</div>
The text-inserter
needs to insert stuff into that textarea
- what's the cleanest angular-ish way to allow that communication? text-inserter
需要在该textarea
插入内容-允许该通信的最简洁的角度方式是什么? I want to be able to support multiple instances of that on the page. 我希望能够在页面上支持该实例的多个实例。 Should I just create a unique id for each one from a shared service? 我是否应该为共享服务中的每个人创建唯一的ID? It seems a little unclean. 似乎有点不干净。
You can : 您可以 :
Use require from the two directive, to, set, the text. 在两个指令中使用require来设置文本。
<div text-com-directive> <text-holder ng-model='model.text' /> <text-inserter> <a ng-click='insert("hello")'>Hello</a> </text-inserter> </div>
Directive : 指令:
directive('textComDirective', function(){
return {
scope:{},
controller: function($scope){
// create functions that will be used to set/use the text inserter.
}
}
});
The only chain between two directives is a variable that is supposed to be updated, this is also used by both directive. 两个指令之间的唯一链是应该更新的变量,两个指令也使用此变量。 The text-inserter directive is sort of like choosing the method to be executed to the text-holder text-inserter指令有点像选择要对文本持有人执行的方法
html html
<text-holder ng-model='model.text'></text-holder>
<text-inserter>
<a ng-click='model.insert("hello")'>Hello</a>
</text-inserter>
script.js script.js
var app = angular.module('testapp',[]);
app.controller('appController', function ($scope) {
$scope.model = {text: 'sample', insert: function(a){$scope.model.text = a}};
})
app.directive('textInserter', function () {
return {
restrict: 'E',
trasclude: true // important to keep the content that is defined outside of directive
}
});
The insert
function is set in the controller that is holding the variable to pass to the directive, this way helps us to easy understand what logic should be applied and is going to happen for the model variable in the initiated scope it self. insert
函数是在控制器中设置的,该控制器持有变量以传递给指令,这样可以帮助我们轻松理解应该应用哪种逻辑,并且对于模型变量在其自身的初始作用域中将会发生什么。 The more benefit is you can situational change the behavior for some specific instance. 更大的好处是您可以根据情况更改某些特定实例的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.