0

I know this have been asked many times, but any of the solutions exposed seem to work for me. I have this HTML

<body ng-controller="mainCtrl">
  <h4>{{size}}</h4>
  <input type="range" ng-model="size" min="1" max="100" />
  <div font-scale="{{size}}">I'm some text</div>
</body>

The input works, the value changes and it is actually binding to {{size}} correctly.

Then I have my directive:

MyApp.controller('mainCtrl', function($scope) {
  $scope.size = 30;
});


MyApp.directive('fontScale', function(){
 return {
   link: function(scope, el, attrs){
     scope.$watch(attrs['fontScale'], function(newVal){
       console.log('testing');
       el.css('font-size', newVal+'px');
     });
    }
   }
 });

The 'testing' shows up in console only once, when the page loads, but when changing the value through the slider, it doesn't. But it DOES bind the value of {{size}} correctly.

Adding 'TRUE' as a third parameter doesn't work, and curiously, the tutorial I'm learning this from works with the same code!

What am I missing?

2
  • The scope in the directive is not the scope in your controller. The directive thus has no clue about the property 'size' so you can not watch a property that is not there. a) ensure that 'size' is available in your scope (read about isolated scopes therefore) and b) specify the watcher as scope.$watch('size'...) Commented Jan 8, 2016 at 15:57
  • The 'size' in the $scope is only for initialization and showing the value. The directive is actually getting the value from the 'font-scale' parameter.. The $scope.size not being in the same scope, shouldn't be a issue. Or at least that is how I understand it if I am not wrong. Commented Jan 8, 2016 at 16:09

1 Answer 1

2

If the size property is available in your directives scope (as stated in your comment). Then the following should work:

scope.$watch('size', function(newVal) {
    el.css('font-size', newVal+'px');
}
Sign up to request clarification or add additional context in comments.

Comments

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.