【问题标题】:bootstrap-timepicker directive not working inside ng-repeatbootstrap-timepicker 指令在 ng-repeat 中不起作用
【发布时间】:2014-03-06 17:31:03
【问题描述】:
Plunker demo
我正在尝试创建任意数量的timepicker,当硬编码时它们工作正常,但当我将它们放入ng-repeat 时它停止工作。有没有办法解决这个问题?
【问题讨论】:
-
我相信这是因为$('.bootstrap-timepicker').timepicker(); 在渲染转发器元素之前正在运行。我添加了一个超时,它可以工作,看看这个fiddle。我不确定 AngularJS 是否有观察者来查看是否所有视图都已呈现。需要调查的东西。
-
-
标签:
angularjs
twitter-bootstrap
angularjs-directive
【解决方案1】:
我刚刚用更好的解决方案更新了我的Plunker。
Tiago answered AngularJS ng-repeat finish event 有一个很好的指令,可以在不使用 $timeout 的情况下解决您的问题
这是指令的副本:
app.directive('myRepeatDirective', function() {
return function(scope, element, attrs) {
if (scope.$last) {
$('.bootstrap-timepicker').timepicker();
}
};
});
HTML:
<li ng-repeat="list in lists" my-repeat-directive>
{{list.name}}
<div class="input-append">
<input type="text" class="bootstrap-timepicker">
<span class="add-on"><i class="icon-time"></i></span>
</div>
</li>
这更好,因为如果您的转发器需要来自 ajax 请求的数据,那么您的超时时间可能必须被更改并导致糟糕的用户体验。
Tiago 的方法似乎处理得最好,在我看来,你可能还想给他一个支持:)
【解决方案2】:
我使用ng-init 解决了这个问题,因为Asok 提供的解决方案对我不起作用。我也不想用$scope
AngularCode
angular.module('MyApp', [])
.controller('MyController', MyController);
function MyController($http) {
// your code here...
jd.InitTime = function () {
$('.bootstrap-timepicker').timepicker();
};
};
HTML
<div data-ng-app="MyApp" data-ng-controller="MyController as mc">
<li ng-repeat="list in mc.lists">
{{list.name}}
<div class="input-append">
<input type="text" class="bootstrap-timepicker" ng-init="mc.InitTime();">
<span class="add-on"><i class="icon-time"></i></span>
</div>
</li>
</div>