Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 指令通信-共享对内部HTML元素的引用_Javascript_Angularjs_Angularjs Directive - Fatal编程技术网

Javascript 指令通信-共享对内部HTML元素的引用

Javascript 指令通信-共享对内部HTML元素的引用,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我想找到一种在我的两个兄弟指令之间进行干净通信的方法。我想为一个指令中的textarea实现insertcaret功能,从另一个指令调用 <text-holder ng-model='model.text' /> <text-inserter> <a ng-click='insert("hello")'>Hello</a> </text-inserter> 文本插入器需要在文本区域中插入内容-什么是允许这种通信的最干净的方式?

我想找到一种在我的两个兄弟指令之间进行干净通信的方法。我想为一个指令中的textarea实现insertcaret功能,从另一个指令调用

<text-holder ng-model='model.text' />
<text-inserter>
    <a ng-click='insert("hello")'>Hello</a>
</text-inserter>
文本插入器需要在文本区域中插入内容-什么是允许这种通信的最干净的方式?我希望能够支持页面上的多个实例。我是否应该为共享服务中的每个服务创建一个唯一的id?看起来有点不干净。

你可以:

在外部DOM元素中包装您的指令。 在此元素上创建通信指令。 将此指令的控制器用作两个指令之间通信的API。 使用两个指令中的require,to,set,text

<div text-com-directive>
<text-holder ng-model='model.text' />
<text-inserter>
    <a ng-click='insert("hello")'>Hello</a>
</text-inserter>
</div>

两个指令之间的唯一链是一个应该更新的变量,这也是两个指令都使用的。文本插入器指令有点像选择要对文本持有者执行的方法

html

insert函数设置在保存变量以传递给指令的控制器中,这种方式有助于我们轻松理解模型变量在其自身启动范围内应该应用什么逻辑以及将要发生什么逻辑。
更大的好处是,您可以根据情况更改某些特定实例的行为。

包装它们似乎不太利于重用,因为我必须记住在使用它们的任何地方包装它们,我更喜欢更接近的解决方案,我可以在元素本身上定义。因此,我了解如何使用共享服务,但如何在同一页面上支持多个共享服务?我怎么说这个文本持有者和那个文本插入器对话?是的,但我不想简单地更新模型,我想在特定的位置插入文本区域插入插入插入符号,模型没有对那个文本区域的引用。我怎样才能得到一个很好的参考呢?@Madd0g我不明白你关于“插入插入符号”的观点。我的观点是更新模型,它也会更新文本区域。你能告诉我一个例子来说明当你得到一个很好的参考资料时,你将如何处理textarea吗?
<div text-com-directive>
<text-holder ng-model='model.text' />
<text-inserter>
    <a ng-click='insert("hello")'>Hello</a>
</text-inserter>
</div>
    directive('textComDirective', function(){
    return {
       scope:{},
       controller: function($scope){
           // create functions that will be used to set/use the text inserter.
       }   
    }
    });
<text-holder ng-model='model.text'></text-holder>
    <text-inserter>
      <a ng-click='model.insert("hello")'>Hello</a>
    </text-inserter>
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
    }
});