3

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.

1 Answer 1

4

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;
          });
        }
      });
    }
  };
});
Sign up to request clarification or add additional context in comments.

6 Comments

Instead of using require I think passing the ngModel into the directive with a two-way binding would be better. Could you explain it in more detail please?
Sorry, I initially attached your javascript and fiddle to the answer. Have amended with mine.
@ktaras, my understanding of using 'require' in a directive is the ability to communicate with another directive's controller. github.com/angular/angular.js/wiki/Understanding-Directives has some good examples of this. Another thing, from your question it looked like you were trying to accomplish two-way binding yourself, when angular can handle this for you.
Oh, I see, thank you! It works perfect and it seems to me like a better solution.
No problems. If you are starting out in Angular check out egghead.io, and also the angular documentation is worth reading docs.angularjs.org/guide/directive
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.