0

Angular v1.2.17

I am creating a directive for formatting the out put using filters. I'm using the directive in another one.

My problem is that the directive does not updates the DOM when the value changes in the parent directive.

I am subscribing to the value variable using scope.$watch.

app.directive('mdmFormattedOut', ['$filter', 'appSettingsService', function($filter, appSettingsService){
return{
    restrict: 'A',
    replace: true,
    template:'<span ng-bind="valueToDisplay"></span>',
    scope:{
        value: '=',
        datatype: '='
    },
    link: function(scope){
        scope.$watch('value', format());
        function format(){
            switch(scope.datatype){
                case 'date':
                    scope.valueToDisplay = $filter('date')(scope.value, appSettingsService.dateFormat);
                    break;
                case 'currency':
                    scope.valueToDisplay = $filter('currency')(scope.value, appSettingsService.currency);
                    break;
                default:
                    scope.valueToDisplay = scope.value;
                    break;
            }
        }
    }
};

}]);

If I replace ng-bind="valueToDisplay" with ng-bind="value" then the things are fine.

What is the catch? Why subscribing manually does not work?

1
  • How are you creating this? <div mdmFormattedOut></div> ? Commented Jul 1, 2014 at 18:13

2 Answers 2

2

The $watch() function expects a callback function as a 2nd argument.
Your code should look like:

scope.$watch('value', format);

Instead of passing a callback, you were passing the return of calling format() which is undefined.

Sign up to request clarification or add additional context in comments.

4 Comments

That's true, this was surely not his intent. But it shouldn't be the reason for not working because the function is still firing and changing the value. See this plunker plnkr.co/edit/YYh0utqsFWfGQKrOj4Ay?p=preview
The function executes once (because you call it explicitly) - this doesn't mean that the $watch works and updates the data when subsequest changes take place.
don't know how I missed that in my answer!
@MohamedElMahallawy: Probably because it was too obvious :)
1

Firstly, from what I understand, you don't need a two-way binding for your scopes.

 scope:{
        value: '@',
        datatype: '@'
    },

Secondly, your template should probably look like this:

<span>{{valueToDisplay}}</span>

1 Comment

That didn't solve the problem, but still you have a point. No need for two way binding!

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.