我尝试使用服务在两个不同的 Controller 之间共享数据并观察变化,但我找不到如何做到这一点。这是我的代码
month-select.component.js:
'use strict'
angular
.module('myApp.monthSelect')
.component('myApp.monthSelect', {
templateUrl: 'monthSelect/month-select.template.html',
controller: 'MonthSelectCtrl',
css: 'monthSelect/month-select.style.css'
})
.controller('MonthSelectCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
selectedMonthSvc.setDate($scope.dt)
}])
weeks-list.component.js:
'use strict'
angular
.module('myApp.weeksList')
.component('myApp.weeksList', {
templateUrl: 'weeksList/weeks-list.template.html',
controller: 'WeeksListCtrl',
css: 'weeksList/weeks-list.style.css'
})
.controller('WeeksListCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
$scope.getDate = selectedMonthSvc.getDate
}])
get-select-month.service.js
angular.module('myApp.svc', [])
.factory('selectedMonthSvc', function () {
var self = this
var date = ''
self.setDate = function (value) {
return date = value
}
self.getDate = function () {
return date
}
return self
})
它在初始化时工作,我在我的 WeeksList Controller 中获取日期,但如果我更改我的 MonthSelectCtrl 中的日期,该值不会在 WeekList 中更新。
我正在尝试使用 $watch 观看它,但它不起作用,也不知道哪里出了问题。
非常感谢您的帮助。
最佳答案
第一次将 factory
更改为 service
:
.service('selectedMonthSvc', function () {/**/}
进一步
您可以编写 watcher
来监听变化。
所以改为:
$scope.getDate = selectedMonthSvc.getDate
尝试:
$scope.getDate = selectedMonthSvc.getDate;
$scope.$watch('getDate', function() {
// here you get new value
});
这是 simple demo 证明你的情况
当第二个 Controller 更新 date
时,第一个 Controller 监听并反射(reflect)更改:
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.getDate();
$scope.$watch(function(){
return App.getDate();
}, function() {
$scope.status = App.getDate();
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.getDate();
$scope.$watch('status', function() {
App.setDate($scope.status);
});
})
.service('App', function () {
this.data = {};
this.data.date = 'someDate';
var self = this;
var date = ''
self.setDate = function (value) {
this.data.date = value
}
self.getDate = function () {
return this.data.date;
}
});
关于Angularjs 观察不同 Controller 中的 ng-model 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46237104/