我有一个模板,它从服务中获取数据。服务中的数据由指令更新。
数据更新后,不会在模板中更新。
// In my template
{{service.get()}}
// In my service
.service('service', function($http){
var _val = 5;
return{
get:function(){
return val;
},
set:function(val){
_val = val;
}
};
});
// In my directive
var someDirective = angular.module('app.someDirective',[]);
someDirective.directive('someDirective', ['service', function(service) {
return function(scope, element, attrs){
$(element).on('scroll', function(event){
service.set(15);
});
};
}]);
如果我在任何其他地方(如其他控制器)调用service.set(x),它可以100%正常工作。
也许有人知道,我做错了什么。 (非常感谢)
修改 为了使它更清楚:
页面加载时,显示“正确”。 但是当值应该更新时,service.set() - 函数被正确调用(来自指令),但模板中没有任何变化。
如果我在其他地方调用service.set(),它就可以工作(值在模板中更新)。
答案 0 :(得分:1)
您的事件发生在摘要周期之外。最简单的解决方法:
$timeout(function() {
service.set(15);
});
答案 1 :(得分:1)
快速解决方法是将集合包装在$timeout
中。事情没有得到更新的原因是因为当$(element).on
触发时,角度不知道运行摘要。另一种解决方法是使用$evalAsync
。