Angular.js中的"scope.watch不是函数"错误

bas*_*ith 3 javascript watch angularjs angularjs-directive angularjs-scope

我已经编写了一个自定义指令来格式化值,下面给出了自定义指令

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;
}
};
}); 
Run Code Online (Sandbox Code Playgroud)

该指令将值格式化为货币,并且它将舍入小数点.我从这些视图中调用了这个指令.

<div class="overallsummary_meter_txt left">
Total Price<br>
<span currency-value items="totalPrice" class="orange_txt"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

这很好用.但是当我通过ajax将值传递给视图时,我发现了一些问题.指令在视图加载的那一刻正在执行,如果值需要时间加载,那么变量将不会有任何值.因此,我从指令中得到一个空值.为了解决这个问题,我稍微修改了我的指令,如下所示.

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;
  });
}
};
}); 
Run Code Online (Sandbox Code Playgroud)

我已经添加了一个scope.watch函数来解决我现有的问题.这适用于所有时刻,我得到格式化和正确的值作为指令的输出.

但作为后续效果,在使用此指令的每个页面中都显示控制台错误scope.watch不是函数

1.如何消除此控制台错误?

2.我应该再次修改指令吗?

Abd*_*oof 5

watch方法命名为$watch.请参阅文档:https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

所以,你应该:

scope.$watch('items', function () {
   scope.items = scope.items ? Math.round(scope.items* 100) / 100 : 0;
});
Run Code Online (Sandbox Code Playgroud)