我在输入 html 元素上调用了以下指令。因此,模板无法像往常一样传播,因为它们的新元素将被包装在输入标记中,该输入标记除了是错误的 HTML 之外,还会将其隐藏在浏览器的 View 中。
return {
restrict: 'A',
scope: {
input: '=ngModel'
},
link: function (scope, element) {
var typeAheadHtml = angular.element('' +
'<div>' +
'{{input}}' +
'</div>' +
'');
element.after($compile(typeAheadHtml)(scope));
}
};
目前,上述工作还不错,因为 typeAheadHtml
只是一个原型(prototype),表明它有效。有没有一种方法可以保持关注点分离,我非常喜欢 AngularJS,但又保持 element.after
的功能。有没有办法让 typeAheadHtml
成为常规的 html 文件?
回答
感谢 DonJuwe 在这方面的帮助。保持相同行为但保持关注点分离的正确方法如下:
link: function (scope, element) {
$http.get('bawwf/templates/type-ahead-directive.html', {cache: $templateCache})
.success(function(html) {
element.after($compile(html)(scope));
});
}
上面的代码从 $templateCache
的文件内容中获取数据。从那时起,像以前一样使用 $compile
提供程序就可以正常工作了。
最佳答案
使用 templateUrl: 'myTemplate.html'
包含您的模板。然后,append 获取 hmtl 并将其附加到 element
中:
$http.get(templateUrl, {cache: $templateCache}).success(function(html) {
element.append(html);
}
更多信息:API Docs
关于javascript - Angular.element.after - 有没有办法让它更干净?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100609/