我从我的服务服务加载了一系列事件:
.directive('appointments', [function () {
return {
restrict: 'CE',
scope: {
ngTemplate: '=',
},
controller: ['$scope','calendarService', function ($scope, calendarService) {
var vm = this;
vm.events = calendarService.getEvents();
}],
controllerAS:'vm',
link: function (scope, elem, attrs) {
scope.getTemplateUrl = function () {
if (angular.isDefined(scope.ngTemplate))
return scope.ngTemplate;
else
return "/list.directive.html";
}
},
template: '<div ng-include="getTemplateUrl()"></div>'
}
}])
现在在另一个指令中我正在更新此列表,如何更新第一个控制器中的列表?
.directive('appointmentsUpdate', [function () {
return {
restrict: 'CE',
scope: {
ngEventId: '=',
},
controller: ['$scope','calendarService', function ($scope, calendarService) {
var vm = this;
vm.update = calendarService.updateEvent(scope.ngEventId).then(function(res){
// Here is where the newly created item, should be added to the List (vm.events) from first directive
)
});
}],
controllerAS:'vm',
link: function (scope, elem, attrs) {
scope.getTemplateUrl = function () {
if (angular.isDefined(scope.ngTemplate))
return scope.ngTemplate;
else
return "/list.directive.html";
}
},
template: '<div ng-include="getTemplateUrl()"></div>'
}
}])
答案 0 :(得分:1)
您可以使用角度广播服务:
第一个指令中的使用:
$rootScope.$broadcast('greeting', data_needs_to_be_send);
在其他指令中监听事件以更新其范围:
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
答案 1 :(得分:0)
我们使用require
属性在指令之间进行通信。
像这样的东西
return {
restrict: 'AE',
require: '^ParentDirective or ^SameLevelDirective'
}
的明确解释
答案 2 :(得分:0)
服务是单例,因此如果您从一个地方(使用calendarService.updateEvent()
)更新列表,那么如果您从另一个指令中的服务检索数据,则它应该是更新的列表。
您可以使用手表检查列表何时更新:
$scope.$watch(() => calendarService.getEvents(), (newValue, oldValue) => {
// update your scope with the new list
}, true);