我有事件从我服务的服务加载列表的diretive:
.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>'
}
}])
这是正确的方法吗? –
是的,你可以做到这一点,并将永远工作,因为它的一个角度特征。但它不仅是你可以使用service.but的方式,但它的超级容易实现。 –
我认为这是两条指令之间沟通的正确途径。使用$ broadcast和$ emit将创建松散耦合的指令。我的建议是使用$ scope。$ broadcast,如果您的'appointmentmentsUpdate'指令是'约会'指令的子元素。 $ rootScope将把事件广播到应用程序中的所有子范围。 –