這裏是我爲我的一個應用程序編寫的示例代碼。
演示:http://plnkr.co/edit/pGhKOTtqFxpD4fukhQrl?p=preview
指令:
app.directive('alert', function(alertService) {
return {
restrict: 'AE',
link: function(scope, e, a, ctl) {
scope.alert = alertService.alertObj;
},
template: '<div class="alert" ng-class="alert.type" ng-show="alert.show">{{alert.msg}}</div>'
};
});
服務:鏈接多個與指令控制器。
app.service('alertService', function() {
var me = this;
me.alertObj = {
show: false,
msg: '',
type: 'alert-success'
};
me.alertShow = false;
me.alertTypes = ['alert-success', 'alert-info', 'alert-warning', 'alert-danger'];
me.alert = function(type, msg) {
me.alertObj.msg = msg;
me.alertObj.type = me.alertTypes[type];
me.alertObj.show = true;
};
me.success = function(msg) {
me.alert(0, msg);
};
me.info = function(msg) {
me.alert(1, msg);
};
me.warning = function(msg) {
me.alert(2, msg);
};
me.danger = function(msg) {
me.alert(3, msg);
};
me.hide = function() {
console.log('hiding');
me.alertObj.show = false;
};
return this;
});
控制器:樣品控制器
app.controller('ctl1', function($scope, alertService) {
$scope.name = 'World';
$scope.showAlert = function() {
alertService.success("This is an success alert");
};
});
HTML:
<alert></alert>
<div ng-controller="ctl1">
<button ng-click="showAlert()">ctl1 - Success alert</button>
</div>
<div ng-controller="ctl2">
<button ng-click="showAlert()">ctl2 - Warning alert</button>
</div>
<div ng-controller="ctl3">
<button ng-click="showAlert()">ctl3 - Danger alert</button>
</div>
<div ng-controller="ctl4">
<button ng-click="showAlert()">ctl4 - Info alert</button>
<button ng-click="hide()">Clear Alert</button>
</div>
哇!我不知道你可以用服務初始化指令,然後在模板中使用服務對象!這是我選擇的答案。 –