AngularJS - 如何向子指令添加功能

AngularJS - How to add functionality to child directive

本文关键字:指令 添加 功能 AngularJS      更新时间:2023-09-26

我有一个指令,其中包含另一个指令。

子指令在我的

应用程序中被广泛使用,而父指令只在一个地方使用。

我想向子指令的 input 元素添加一个绑定。但是,仅当指令放置在父指令中时才需要此绑定,而不是将其用作独立指令时需要此绑定。

现在我想知道最好的方法。

我想过循环我的父指令的子节点,直到我到达input,然后绑定到它。但是,这将导致一个令人困惑的、令人困惑的过程,如下所示:

 $element.find('suggestion').childNodes[0].childNodes[1] // ... and so on

如果我尝试直接查找输入,我会得到一个空对象。

这是要走的路还是我不知道更好的方法?

一般方法是使用父指令的控制器并将"suggestion"添加到作用域中。Angular 通过 ng-model='suggestion' 绑定您的子指令。

您的父指令将是这样的:

angular.module('yourappname').directive('parentdirective',function(){
   return {
      .....
      controller: 'ParentCtrl',
      .....
   }
}

您的控制器:

angular.module('controller', function($scope){
   $scope.suggestion // note that setting primitives directly on the scope is not recommended
 }

您的孩子指令:

<input ... ng-model="suggestion" />