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

标签 javascript angularjs angularjs-directive angularjs-ng-repeat

我正在尝试创建一个指令,该指令最终将成为“自动完成”并在表单元素下方显示数据。

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

在指令中,我正在监视等待填充数据的 attr,填充后,我将其设置为指令中的变量,并尝试 ng-repeat 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");
                }

            });
        }
    }

最佳答案

好吧,我发现这段代码中存在一些错误,导致它无法 工作。见下文:

  • 在您的链接中,cdata不在范围内,因此无法通过 HTML 访问
  • data 包含一个数组而不是字符串,因此您不能将其插入为 data="{{stuff}}"
  • 相反,您需要 $watch 查找 attr.data
  • 由于您向范围添加了信息,因此它应该是使用 scope: true 的新范围

可能就是这样,请参阅修复的plunkr:http://plnkr.co/edit/K9D9h8SYaqNw3uKui1xT?p=preview

关于javascript - AngularJS : directive ng-repeat doesn't work in link function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30247503/

相关文章:

javascript - ng-repeat 与 ng-hide 或在 Controller 中执行此操作以提高性能?

javascript - 如何为单个文本字段设置占位符文本颜色的样式?

javascript - 带有 if 语句的 For 循环不会运行多次 javascript

javascript - 将 Bootstrap 单选按钮绑定(bind)到 Angular 属性

angularjs - 需要嵌套在父指令 AngularJS 中的指令 Controller

javascript - 自定义指令未在指定的 DOM 位置呈现

angularjs - Replace=false 的 Angular 指令创建非语义的列表 html

angularjs - 使用指令将 ngModel 添加到输入

javascript - 终止于 D3 中节点边界的链接和箭头

javascript - 不需要的页面重定向