我在我的应用程序中遇到了多次触发共享数据服务的问题,现在我将尝试解释它。
在带有 Controller “home”的主页上,用户可以选择三个菜单项之一,在用户选择其中一个项目(例如第一个)后,他将重定向到此 View ,并具有自己的 Controller “table” '。该 View 底部有一个表格和选项卡,每个选项卡都有自己的 Controller “tab1 等”。通过单击行,我在选项卡的 Controller 之间共享该行的 id,该选项卡可以加载与该特定行相关的内容。目前一切进展顺利。
接下来,当用户单击主页按钮时,他将重定向到主页,如果他再次单击项目(例如第一个项目),共享服务将触发两次,并返回相同的 ID 两次,这是第三次分享服务会触发3次等等
在我的代码下面,如果有人能解释我所缺少的内容,我将不胜感激。提前致谢。
app.controller('table', [
'$scope', 'tab1ID', 'tab2ID', 'tab3ID'
function ($scope, tab1ID, tab2ID, tab3ID) {
$scope.rowSelection($scope, function (row) {
tab1ID.setId(row.id);
tab2ID.setId(row.id);
tab3ID.setId(row.id)
});
app.controller('tab1', [
'$scope', 'tab1ID', dataService
function ($scope, tab1ID, dataService) {
tab1ID.getId().then(null, null, function (id) {
// return increment count of 'id' after redirecting from home view to table view
// dataService firing for each incremented id (1 for 1, 2 for 2 and etc)
dataService.rowData(id)
.then(function (res) {
$scope.data = res;
})
});
.factory(
'tab1ID', function ($q) {
var self = this,
defer = $q.defer();
this.share = '';
return {
getId: function () {
return defer.promise;
},
setId: function (id) {
self.share = id;
defer.notify(self.share);
}
}
}
);
最佳答案
所以最后我想出了如何击败多重触发。我为即将到来的 id 添加了一个新变量声明,并设置 Angular 监视来跟踪该变量的变化。也许这是一个丑陋的方法,但它对我有用
tab1ID.getId().then(null, null, function(id){
$scope.id = id
});
$scope.$watch('id', function (newVal, oldVal) {
if (typeof newVal !== 'undefined') {
dataService.rowData(id)
.then(function (res) {
$scope.data = res;
})
})
关于javascript - AngularJS,共享数据服务多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107945/