2

我想创建一个指令,最终将是一个“自动完成”,并在表单元素下显示数据。AngularJS:指令NG - 重复不起作用的链接功能

我有一个问题,在插入的html中获取ng-repeat以显示它从attr获取的信息数组。

在指令中我监视attr等待数据填充,一旦它被填充,我将它设置为指令中的一个变量,并尝试ng-重复ul html中的数据。即使该变量已填充到指令中,也没有显示任何内容。

任何想法为什么?我试过做很多事情,我确定这是一个父/子范围问题,只是不知道我需要改变什么?我试图保持隔离的指令范围,所以我可以重复使用这个指令多次。

Plunker:http://plnkr.co/edit/XoXli0OyRP6xObsDImOe

//Directive 
    function autoComplete($parse, $compile, $timeout) { 
     var directive = { 
      restrict: 'EA', 
     // scope: true, 
      require: '?ngModel', 
      link: link 
     }; 

     return directive; 

     function link(scope, elem, attr, ngModel) { 
      var cdata = []; 

      var modelGet = $parse(attr['ngModel']); 
      var modelSet = modelGet.assign; 


      scope.$watch(function() { 
       return elem.attr('data'); 
      }, function(newVal) { 
       cdata = newVal; 
       console.log(cdata); 
      }); 

      $timeout(function(){ 

       //var ewidth  = elem.outerWidth(); //Doesn't work in Plunker for some reason 
       var ewidth = '100%'; 
       var html  = '<div><ul class="list-group" style="position: absolute; width: '+ewidth+'px;"><li class="list-group-item" ng-repeat="codes in cdata track by $index">{{codes.code}}</li></ul></div>'; 
       elem.after($compile(html)(scope)); 
       scope.$apply(); 
       console.log("DIV has been added"); 
      }); 



      scope.$watch(function() { 
       return modelGet(scope); 
      }, function() { 
       var string = modelGet(scope); 
       if (string != undefined && string.length >= 6) { 
        console.log("Will do something later"); 
       } 

      }); 
     } 
    } 

回答

2

好吧,我发现了错误的组合在这段代码,使得它不 工作。请看下图:

  • 在你linkcdata不在范围,所以无法通过HTML
  • data包含一个数组,而不是一个字符串进行访问,所以你不能为data="{{stuff}}"
  • 插值相反,你需要为$watchattr.data
  • 既然你的范围添加信息,它应该是使用scope: true

可能是这样吧,请参阅固定plunkrhttp://plnkr.co/edit/K9D9h8SYaqNw3uKui1xT?p=preview

+0

谢谢,我新我很接近。我还没有足够使用AngularJS来理解父/子范围。 – Speedy059