繁体   English   中英

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

[英]Directive communication - sharing a reference to an inner HTML element

我想找到一种在两个兄弟指令之间进行干净通信的方法。 我想在一个指令中为一个文本区域实现“ insertAtCaret”功能,该指令可以从另一个指令中调用。

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

text-holder变成这样的事情:

<div class='my-class'>
    <h3>Enter some text:</h3>
    <textarea ng-model='ngModel'></textarea>
</div>

text-inserter需要在该textarea插入内容-允许该通信的最简洁的角度方式是什么? 我希望能够在页面上支持该实例的多个实例。 我是否应该为共享服务中的每个人创建唯一的ID? 似乎有点不干净。

您可以 :

  • 将指令包装在外部DOM元素中。
  • 在此元素上创建通信指令。
  • 将此指令的控制器用作两个指令之间进行通信的API。
  • 在两个指令中使用require来设置文本。

     <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-inserter指令有点像选择要对文本持有人执行的方法

html

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

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
    }
});  

样品

insert函数是在控制器中设置的,该控制器持有变量以传递给指令,这样可以帮助我们轻松理解应该应用哪种逻辑,并且对于模型变量在其自身的初始作用域中将会发生什么。 更大的好处是您可以根据情况更改某些特定实例的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM