AngularJS:指令ng-repeat在link函数中不起作用

AngularJS : directive ng-repeat doesn't work in link function

本文关键字:函数 不起作用 link 指令 ng-repeat AngularJS      更新时间:2023-09-26

我试图创建一个指令,最终将是一个"自动完成"和显示表单元素下的数据。

我在插入的html中获得ng-repeat以显示它从attr获得的信息数组时遇到了问题。

在指令中,我正在监视attr等待数据被填充,一旦它被填充,我将其设置为指令中的变量,并尝试在ul html中重复数据。即使在指令中填充了变量,也不会显示任何内容。

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

砰砰作响: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");
                }
            });
        }
    }

好吧,我在这段代码中发现了一个错误组合,使它不能工作。见下文:

  • 在你的link中,cdata不在作用域上,所以不能被HTML
  • 访问
  • data包含一个数组而不是字符串,所以你不能插入data="{{stuff}}"
  • 相反,你需要$watchattr.data
  • 由于您向作用域添加了信息,它应该是一个使用scope: true
  • 的新信息。

这可能是它,见fixed plunkr: http://plnkr.co/edit/K9D9h8SYaqNw3uKui1xT?p=preview