我正在尝试创建一个指令,该指令最终将成为“自动完成”并在表单元素下方显示数据。
我在插入的 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/