AngularJS指令,使用JavaScript操作模板

AngularJS指令,使用JavaScript操作模板,angularjs,angularjs-directive,jquery-ui-progressbar,Angularjs,Angularjs Directive,Jquery Ui Progressbar,我试图通过AngularJS指令实现,但我遇到了一点麻烦,我觉得我可能只是没有理解指令中提供的过多配置选项。基本上,我希望能够做到以下几点: <div ng-repeat="te in timedEvents"> <progressbar identifier="{{te.identifier}}" begins="{{te.beginTimestamp}}" ends="te.endTimestamp" now="td.nowTimestamp"></pr

我试图通过AngularJS指令实现,但我遇到了一点麻烦,我觉得我可能只是没有理解指令中提供的过多配置选项。基本上,我希望能够做到以下几点:

<div ng-repeat="te in timedEvents">
    <progressbar identifier="{{te.identifier}}" begins="{{te.beginTimestamp}}" ends="te.endTimestamp" now="td.nowTimestamp"></progressbar>
</div>
myApp.directive('progressbar', function($compile) {
    return {
        restrict: 'E',
        scope: {
            identifier: '@identifier'
        },
        template: "<div id='{{identifier}}'></div>",
        link: function (scope, element, attrs) {
            var percentComplete = --whatever--; //calculate this, obviously
            $("#" + attrs.identifier).progressbar({
                value: percentComplete;
            });
            //do other stuff to set a proper interval for keeping this updated
        }
    }
})

事件是异步来自服务器的(不确定这是否重要)。然后有一个类似这样的指令:

<div ng-repeat="te in timedEvents">
    <progressbar identifier="{{te.identifier}}" begins="{{te.beginTimestamp}}" ends="te.endTimestamp" now="td.nowTimestamp"></progressbar>
</div>
myApp.directive('progressbar', function($compile) {
    return {
        restrict: 'E',
        scope: {
            identifier: '@identifier'
        },
        template: "<div id='{{identifier}}'></div>",
        link: function (scope, element, attrs) {
            var percentComplete = --whatever--; //calculate this, obviously
            $("#" + attrs.identifier).progressbar({
                value: percentComplete;
            });
            //do other stuff to set a proper interval for keeping this updated
        }
    }
})
myApp.directive('progressbar',function($compile){
返回{
限制:'E',
范围:{
标识符:“@identifier”
},
模板:“”,
链接:函数(范围、元素、属性){
var percentComplete=--随便什么--;//显然,计算一下这个
$(“#”+attrs.identifier).progressbar({
值:完成百分比;
});
//执行其他操作以设置适当的时间间隔来保持此更新
}
}
})
问题在于,link函数中的代码在模板创建的DOM元素准备就绪之前执行,因此如果您试图通过JQuery或其他方式访问上述DIV,您只会返回未定义的状态。解决这个问题的方法是简单地设置一个超时,以便在找到元素之前继续尝试(通常需要不到一秒的时间)。不过,我只是想知道,是否有办法通过指令本身来实现这一点,这样它只会在模板内容正确放入页面后尝试执行JavaScript代码


有人能回答这个问题吗?

您是否研究过progressbars的angular ui指令?可能更有意义。你不能在进度条上使用$watch,然后只有当它不为空时,你才会激活进度条功能吗?你是否尝试过注入
$document
并执行
$document.ready(…)
类似于jQuery,或者如果你使用
ng视图
,你可以使用
作用域。$on($viewContentLoaded)
function但如果我错了,请纠正我,您可能应该在您的情况下编译函数而不是链接,因为您正在转换模板中的DOM?@Sharondio-Wow!不,我没有看过UI引导项目。那会让我的生活轻松很多。非常感谢。我可能会用这个。提琴手——也许吧。我可能会玩弄它。大卫·蔡斯——我对编译和链接之间的区别感到困惑。我认为文档中提到,您可以在这两种方式中操作DOM,所以我不明白为什么您更喜欢其中一种方式。