Reputation: 3142
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?
Upvotes: 0
Views: 96
Reputation: 48212
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
.
Upvotes: 2
Reputation: 13842
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>
Upvotes: 1