gpt4 book ai didi

javascript - 如何访问指令中的范围集合对象以手动构造 HTML 片段?

转载 作者:行者123 更新时间:2023-11-30 10:25:43 24 4
gpt4 key购买 nike

关注来自 How to pass a collection to a directive in angular.js? 的问题

我不能在我的指令模板中使用 ng-repeat,因为我需要手动构造一个 HTML 片段以传递给我包装在指令中的 jQuery 插件。 https://github.com/aehlke/tag-it

在下面的示例中,我要么需要 1) 找到一种在呈现模板后应用 elem.tagIt() 的方法,要么 2) 在指令中访问 tagSrc 以构建该 HTML 片段,然后将其添加到 elem。 html() 在应用 elem.tagIt() 之前。

app.directive('tagIt', function (){
return {
restrict: 'A',
scope: { tagSrc: '='},
template: '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
link: function(scope,elem, attr) {
//tagIt() is a reference to jQuery plugin that turns LIs in to stackoverflow-style tags
elem.tagit(); //tagIt is not applied to the right DOM contents because ng-repeat hasn't written it out yet
console.log(attr.tagSrc);
}

}});

最佳答案

您的标签可以通过 scope.tagSrc 访问,但当您的指令链接时它们可能还没有准备好。

为了在 tagSrc 改变时调用它,使用 scope.$watch:

scope.$watch('tagSrc', function(){
elem.tagIt();
});

关于javascript - 如何访问指令中的范围集合对象以手动构造 HTML 片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19645531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com