Reputation: 417
I'm a beginner in AngularJS and have some HTML & JS code here:
http://jsfiddle.net/ktaras/v9sjL/7
Could somebody help me and explain why ngModel.$modelValue
in my link
function returns NaN
?
I found some solution and getting model value from scope.$eval(attrs.ngModel)
, but it seems to me so far from perfect...
Please, explain me how to do it properly.
Upvotes: 3
Views: 1709
Reputation: 5725
I suspect it has something to do with the digest cycle, as if you wrap console.log(ngModel.$modelValue); within a $timeout (once injecting it into the directive) it evaluates fine. But this is hacky and would not recommend.
Instead of using require I think passing the ngModel into the directive with a two-way binding and attaching to the directives scope would be better.
Fiddle: http://jsfiddle.net/PRg5h/1/
HTML:
<div ng-app="myApp">
<div ng-controller="myController">
Rating: {{rating}}
<div slider ng-model="rating"></div>
</div>
</div>
JavaScript:
var myApp = angular.module("myApp", []);
myApp.controller('myController', function($scope){
$scope.rating = 50
});
myApp.directive('slider', function() {
return {
restrict: 'A',
scope: {
ngModel: '='
},
link: function(scope, elem, attrs) {
console.log(scope.ngModel);
return $(elem).slider({
range: "min",
animate: true,
value: scope.ngModel,
slide: function(event, ui) {
return scope.$apply(function(){
scope.ngModel = ui.value;
});
}
});
}
};
});
Upvotes: 4