【问题标题】:"scope.watch is not a function" error in Angular.jsAngular.js 中的“scope.watch 不是函数”错误
【发布时间】:2016-12-02 09:42:47
【问题描述】:

我已经编写了一个自定义指令来格式化值,自定义指令如下所示

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;
}
};
}); 

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

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

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

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;
  });
}
};
}); 

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

但作为此之后的结果,在使用该指令的每个页面中都会显示控制台错误 scope.watch is not a function

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

2.是否需要再次修改指令?

【问题讨论】:

  • 应该是$watch,而不是watch
  • 它是scope.$watch 而不是$scope.watch

标签: javascript angularjs angularjs-directive angularjs-scope watch


【解决方案1】:

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;
});

【讨论】:

  • 我对代码进行了更改,控制台错误不再存在。但是有些页面我得到“0”作为指令的输出,这可能是由于在获取变量项的值之前执行了指令,但我已经包含了这个范围。$watch 来克服这个.. 是还有其他方法可以解决所有这些问题
猜你喜欢
  • 2016-08-31
  • 2023-03-15
  • 2018-03-07
  • 2016-08-08
  • 2018-07-01
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多