Итак, я хочу создать директиву, которая выводит глобальное сообщение.Создание системы сообщений «App-Wide» в Angular
Требования директивы ...
Эта директива сообщения может обновляться с любого контроллера.
Когда сообщение обновляется с любого контроллера, таким образом, это директива, следовательно, вид.
Очистить сообщение после того, как точка зрения destoryed
До сих пор я делаю это путем создания директивы и обслуживания, которые работают вместе. Проблема: я не могу обновить представление, когда сообщение обновляется из других контроллеров.
Если кто-то может направить меня на то, как действовать, что будет набухать. Как насчет использования $ rootScope и трансляции?
app.directive("alertMsg", ['MsgService', function(MsgService) {
return {
restrict: "E",
scope: true,
template: '{{msg}}', // this string is the html that will be placed inside the <alert-msg></alert-msg> tags.
link: function (scope, $element, attrs) {
scope.msg = MsgService.getAlertMsg(); //set msg to be available to the template above <alert-msg>{{msg}}</alert-msg>
scope.$on("$destroy", function(){ //when the <alert-msg> view is destroyed clear the alert message
MsgService.clearAlertMsg();
});
}
};
}]);
app.service('MsgService', function() {
this.alertMsg = '';
this.getAlertMsg = function(){
return this.alertMsg;
};
this.setAlertMsg = function(string) {
this.alertMsg = string;
};
this.clearAlertMsg = function(){
this.alertMsg = '';
};
});
app.controller('NewPlateController', ['urlConfig', '$scope', '$http', '$location', 'MsgService', '$routeParams', function(urlConfig, $scope, $http, $location, MsgService, $routeParams) {
$scope.plate = {license_plate: $routeParams.plate, state: 'default-state'};
// create new plate via json request
$scope.createPlate = function(){
$http.post(urlConfig.rootUrl+"/plates.js", $scope.plate).success(function(data) {
$scope.plateInfo = data;
MsgService.setAlertMsg('Plate Sucessfully Created'); //Need to update the directive to actual show this update
$location.path('/plate/'+$scope.plateInfo.plate_id);
// http error: display error messages
}).error(function(data,status,headers,config) {
$scope.errors = data;
$('#new-plate-errors').slideDown('fast');
});
};
}]);
Я думаю, что ваша идея $ rootScope и вещания звучит нормально. – Kolban
Я думал, что было бы проще и чище использовать $ rootScope, но я не уверен, как это сделать. Смогу ли я использовать директиву, но не услугу? – JerryA