Reputation: 5704
I am trying to create jQuery mobile directive for Angularjs.
Here's what I come up so far:
The code for AngularJS directive:
mcb.directive('jSlider', function () {
return {
scope: {
id: '@',
label: '@',
value: '=',
min: '@',
max: '@',
step: '@',
disabled: '@',
mini: '@',
highlight: '@'
},
restrict: 'A',
replace: false,
templateUrl: 'tpl/widget/jslider.htm',
link: function(s, e, a) {
e.trigger('create');
}
};
});
Template for the directive:
<label for="{{id}}">{{label}} </label>
<input class="slider"
type="range"
name="{{id}}"
id="{{id}}"
data-highlight="{{highlight}}"
min="{{min}}"
max="{{max}}"
data-ng-model="value"
/>
This code creates the the directive but it's not working, I think the problem is that it doesn't compile properly. I tried add adding
compile: function (e, a) {
e.trigger('create');
},
inside directives code, then it kinda worked? (it added properties and everything), but slider is displayed at 0 point, event though I set different, value. I think the problem is that I need to refresh slider when value is set or changed in some way other that slide event (which is important for application I am building). I tried refreshing slider with this code:
compile: function (e, a) {
e.trigger('create');
e.find('.slider');
},
but it doesn't work, and the code inside "link" function stops working when I add "compile" function.
I am new to angularjs, so I don't quite know how "compile" and "link" functions work, it would be nice if someone could give some references to simple explanation, I think I will need it because I will be needing to attach, start, slide, stop events to the directive. Anyway, any suggestion, how to solve this problem?
Upvotes: 0
Views: 416
Reputation: 5704
After many tries I come up with solution that works:
mcb.directive('jSlider', function () {
return {
scope: {
id: '@',
label: '@',
value: '=',
min: '@',
max: '@',
step: '@',
disabled: '@',
mini: '@',
highlight: '@',
start: '&',
stop: '&'
},
restrict: 'A',
replace: false,
templateUrl: 'tpl/widget/jslider.htm',
compile: function (e) {
e.trigger('create');
return {
post: function (s, e, a) {
e.find('a').click(function (e) {
return e.preventDefault();
});
e.find('div.ui-slider').find('input[type="range"]').on('slidestop', function () {
return s.stop();
});
e.find('div.ui-slider').find('input[type="range"]').on('slidestart', function () {
return s.start();
});
e.find('div.ui-slider').find('input[type="number"]').change(function () {
return s.stop();
});
s.$watch('value', function () {
return e.find('#' + a.id).slider('refresh');
});
}
};
}
};
});
Upvotes: 1