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

标签 javascript angularjs angularjs-directive

关注来自 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/

相关文章:

javascript - 使用 JavaScript 将路径转换为嵌套无序列表 :

javascript - 在带有图例的引导模式中显示 donut /饼图

AngularJS/UI ui-sortable 没有隔离范围?

javascript - 将 ng-model 值设置为 div 文本

javascript - Angularjs ng-click() 不是从 ng-repeat 指令触发

angularjs - 用于包装 JavaScript 库的 AngularJS 模块

javascript - 转到其他 URL 后如何保持 Backbone.js 集合的排序?

javascript - 有没有办法让 div 像 iframe 一样工作?

javascript - Angular 创建 "third party module"、处理数据或获取数据?

angularjs - 将链接从移动网络浏览器迁移到移动应用程序