[英]Why is my $watch function returning undefined?
Here is my watch function, below... it's currently watching a function in my ViewFactory. 这是我的监视函数,下面...当前正在监视ViewFactory中的函数。
// Watch for when tagsFilterModal is showing:
vs.$watch('ViewFactory.retrieveSavedViews()', function(newVal) {
console.log("New Data", newVal);
});
The retrieveSavedViews()
function calls an API and returns data: retrieveSavedViews()
函数调用一个API并返回数据:
function retrieveSavedViews() {
console.log('retrieveSavedViews called...');
ApiFactory.getViews().then(function(data) {
if (data.data.status === 'Success') {
// Store views locally:
return storeSavedViews(data.data.views);
// Populate load view dropdown:
}
});
}
^ you can see above that I return another function storeSavedViews()
: ^您可以在上面看到我返回了另一个函数storeSavedViews()
:
function storeSavedViews(data) {
savedViews = data;
console.log('storeSavedViews savedViews',savedViews);
return savedViews;
}
How am I using the $watch
service wrong here? 我在这里如何使用$watch
服务错误?
I advice you - nearly never use $watch on functions. 我建议你-几乎不要在函数上使用$ watch。 Because then function will launch in each digest cycle. 因为这样,功能将在每个摘要周期中启动。 Look this example . 看这个例子 。
There is simple $scope.$watch('test()')
, and you see that test()
launches if I change another scope variable and you can not control this. 有一个简单的$scope.$watch('test()')
,如果我更改另一个作用域变量并且您无法控制它,您会看到test()
启动。
What you should do is to store promise to object: $scope.object = Service.get()
and watch it. 您应该做的是存储对对象的承诺: $scope.object = Service.get()
并对其进行监视。 Quite often you can leave watcher creation to angular and just have in html: 通常,您可以将观察者的创建留给有角度的内容,而仅包含在html中:
<div ng-if="!object.$resolved">Retrieving data...
</div>
<div ng-if="object.$resolved">Got data {{object}}
</div>
And if you need some specific actions to be done after async call finishes - you better provide callback function. 并且,如果您需要在异步调用完成后执行一些特定的操作,则最好提供回调函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.