原因是你使用的所有jQuery插件都會在頁面加載後儘快啓動自己。但是在此之後的一段時間裏,Angular會填充<ng-view/>
。解決方案是手動啓動插件。角度的方式是爲每個「特殊」元素創建自己的指令,並應用相應的jQuery插入其中的link
函數。讓我們用一個日曆,例如:
app.directive('calendar', function(){
return {
template: '<div class="calendar"></div>',
link: function(scope, el, attrs, ctrl){
$(el).makeCalendar();
}
}
})
這樣,您就可以使用<calendar></calendar>
在你的HTML創建日曆。
編輯
謝謝你的答案,但也許我不明白......
例如,在的document.ready我這樣做:
$doc.ready(function() {
var $sliderRange = $('#slider-range');
var $amount = $('#amount');
if ($sliderRange.length) {
// apply range slider
$sliderRange.slider({
range: true,
min: 0,
max: 3000,
values: [0, 2600],
slide: function(event, ui) {
$amount.val('€' + ui.values[0] + ' - €' + ui.values[1]);
}
});
$amount.val('€' + $sliderRange.slider('values', 0) + ' - €' +
$sliderRange.slider('values', 1));
}
});
我怎麼能用指令做到這一點?
例:
app.directive('slider', function(){
var defaults = {
range: true,
min: 0,
max: 3000,
values: [0, 2600],
};
return {
template: '<div></div>',
replace: true,
scope: {
options: '=',
value: '='
},
link: function(scope, el, attrs, ctrl){
// merge options with defaults
var opts = ng.extend({}, defaults, scope.options);
// set initial value
opts.values = scope.value = scope.value || [0, 0];
// watch for changes and update the scope's value
opts.slide = function(event, ui){
scope.value = ui.values;
scope.$apply();
};
// apply the jquery plugin with the options
$(el).slider(opts);
}
}
})
現在你使用它像:
<slider value="sliderValue"></slider>
<p>Result: €{{sliderValue[0]}} - € {{sliderValue[1]}}</p>
而且你可以修改這樣的選項:
<slider value="sliderValue" options="{max: 100}"></slider>