Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"scope.watch is not a function" error in Angular.js

I have written a custom directive to format values, The custom directive is given below

var directiveapps = angular.module('myApp.currencyValues', []);
directiveapps.directive('currencyValue', function () {
return{
scope: {
    data: '=items'
},
template: '<div>$ {{value|number}}</div>',
link: function(scope){
  scope.value = Math.round(scope.data* 100) / 100;
}
};
}); 

This directive will format a value to a currency and also it will round off the decimal points. And i have called this directive from the view like these.

<div class="overallsummary_meter_txt left">
Total Price<br>
<span currency-value items="totalPrice" class="orange_txt"></span>
</div>

This works fine. But i figured out some issues when the value is passed to the view through ajax.The directive is executing at the very moment of view loading, if the value takes time to load then there will not be any value at the variable items. As a result of this i'm getting a empty value from the directive. To solve this issue i have slightly modified my directive as given below.

var directiveApps = angular.module('gogocarApp.currencyValues', []);
directiveApps.directive('currencyValue', function () {
return {
transclude: true,
scope: {
  items: '=items'
},
template: '<div>$ {{items|number}}<span ng-transclude></span></div>',
link: function(scope){
  scope.watch('items', function () {
   scope.items = scope.items ? Math.round(scope.items* 100) / 100 : 0;
  });
}
};
}); 

i have added a scope.watch function to solve my existing issues.This works fine for all instants and i'm getting formatted and correct values as the output of the directive.

But as an after effect of this, in every page which uses this directive shows a console error scope.watch is not a function

1.How can i Eliminate this console error?

2.Should i need to modify the directive again?

like image 276
basith Avatar asked Jan 24 '26 17:01

basith


1 Answers

watch method is named as $watch. Refer the docs: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

So, you should have:

scope.$watch('items', function () {
   scope.items = scope.items ? Math.round(scope.items* 100) / 100 : 0;
});
like image 60
Abdel Raoof Olakara Avatar answered Jan 26 '26 06:01

Abdel Raoof Olakara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!