繁体   English   中英

通过自己的链接器功能编译指令

[英]Compiling directive from its own linker function

我有一个指令设置,如下所示:

angular.module('RecursiveDirective', []).
directive('item', function($compile) {
  return {
    restrict: 'E',
    template: '<div><input type="text" ng-model="itemvalue"/></div>',
    link: ItemLinker,
    controller: 'ItemController',
    scope: {}
  }

  function ItemLinker(scope, element, attribute) {
    element.on('keyup', function(event) {
      var code = event.keyCode || event.which;
      if(code==13) {
        element.append('<item></item>');
        $compile(element.contents())(scope);
      }
    })
  }
}).
controller('ItemController', function($scope) {
  $scope.itemvalue = "Some Value";
})

现在,我试图在此指令元素上按下Enter键时克隆该元素。

我能够克隆该指令,但不能正确设置范围。 从第二次克隆开始,伪指令将重置其克隆所涉及的伪指令上的先前设置的值。

我如何克隆该指令,以便它获得自己的新作用域,如新初始化的指令。

在这里Plunker-http://plnkr.co

编辑

我必须使用指令(即包含另一个指令项的指令项)创建嵌套结构。 上面的问题是相同的线性表示。

所以,我不能在这里使用ng-repeat 谢谢

element.on('keyup', function(event) {
  event.stopPropagation();

如果不停止传播,则事件冒泡,最终您将再次编译每个元素,并多次添加每个添加的项

我认为您不应该创建递归指令。 您可以像这样创建一个ng-repeat:

<item ng-repeat='item in vm.items'></item>

然后检查输入并在vm.items添加其他项目

试试这个矮子

 // Code goes here angular.module('RecursiveDirective', []). directive('item', function($compile) { return { restrict: 'E', template: '<div ng-repeat="itemvalue in inputs track by $index"><input ng-keyup="keyUp($event)" type="text" ng-model="itemvalue.value"/></div>', link: ItemLinker, controller:"ItemController", scope: {} } function ItemLinker(scope, element, attribute) { scope.keyUp = function(event){ if(event.keyCode==13) { scope.inputs.push({value:""}); } } scope.inputs =[{value:scope.itemvalue}]; } }). controller('ItemController', function($scope) { $scope.itemvalue = "Some Value"; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!DOCTYPE html> <html> <head> <script src="https://code.angularjs.org/1.4.9/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-app="RecursiveDirective"> <div></div> <item></item> </body> </html> 

暂无
暂无

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

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