gpt4 book ai didi

javascript - Angular : Watch scope value of a injected service changed in one directive from another directive

转载 作者:行者123 更新时间:2023-11-29 17:00:20 26 4
gpt4 key购买 nike

考虑以下场景。

有两个相互独立的指令,我想共享这两个指令之间的范围。由于它们没有嵌套,我不能在指令中使用 Controller 来共享范围。所以我创建了一个服务并将该服务注入(inject)到这两个指令中。

因此,当服务的值在一个指令中更改时,我需要在另一个指令中更新相同的值。我怎样才能做到这一点?我希望以棱 Angular 分明的方式正确完成这项工作,没有反模式。

这是我目前的尝试

.directive('d1', ['cData', function() {
return {
link: function() {
// this watch is not working
scope.$watch( function() {
return cData.Value;
}, function(newValue, oldValue) {
alert(newValue);
})
}
}
})
.directive('d2', ['cData', function() {
return {
link: function() {
element.on('click', function() {
cData.Value = false
scope.$digest();
});
// A watch here is working, I have commented it out
/*scope.$watch( function() {
return cd.showStatus;
}, function(newValue, oldValue) {
alert(newValue)
})*/
}
}
}])
.service('cData', function() {
this.Value = false;
})

我在指令 d2 的点击事件中更新服务的值我需要在指令 d1 中触发 watch .可能这不起作用,因为两个指令的范围不同。我怎样才能做到这一点,非常感谢任何帮助。

更新

指令模板 d1

template : '<div ng-class="{show:cData.Value==true}"></div>'

更新{show:cData.Value==true}

我必须在指令 d1 的事件监听器中再次调用 scope.$apply()

希望这是正确的做法。

最佳答案

你走在正确的道路上,但我建议使用 $broadcast 而不是添加新的 $watch。添加一个新的观察者更像是一个局部范围的解决方案(至少在我看来是这样)。所以这一切都归结为在两个独立对象之间共享数据。你可以这样实现:

.directive('d1', ['cData', function() {
return {
link: function(scope) {
// this watch is not working
scope.$on('data:changed', function(e, data) {
alert(data);
}
/*
scope.$watch( function() {
return cData.Value;
}, function(newValue, oldValue) {
alert(newValue);
}) */
}
}
})
.directive('d2', ['cData', '$rootScope', function() {
return {
link: function() {
element.on('click', function() {
$rootScope.$broadcast('data:changed', { value: false });
// cData.Value = false
// scope.$digest();
});
// A watch here is working, I have commented it out
/*scope.$watch( function() {
return cd.showStatus;
}, function(newValue, oldValue) {
alert(newValue)
})*/
}
}

}])

从我的 Angular 来看,这是实现独立对象/指令之间通信的最干净的方式,没有太多麻烦。而且代码非常干净且分离。

你怎么看?

关于javascript - Angular : Watch scope value of a injected service changed in one directive from another directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28805223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com