2013-06-28 42 views
2

在AngularJS中爲所需控制器添加通用通知功能的最佳方式是什麼?AngularJS-way:使用通知功能擴展控制器/視圖

目標是創建可輕鬆添加/刪除任何控制器的本地通知。

所以:

  1. 現在共享的功能控制器之間
  2. 這個功能應該工作與視圖輸出 通知

我們(怎麼不知道?)有such solution

code there 
+0

創建一個通知服務並注入控制器 –

+0

它是(1)的答案,但你對(2) –

+0

的建議是什麼?你需要解釋一下你想達到什麼樣的情景以及你想要顯示或發送什麼類型的通知 –

回答

0

我喜歡在UI引導執行(從角UI團隊)的方式:http://angular-ui.github.io/bootstrap/#/alert

<div ng-controller="AlertDemoCtrl"> 
    <alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">{{alert.msg}}</alert> 
    <button class='btn' ng-click="addAlert()">Add Alert</button> 
</div> 

<script> 
function AlertDemoCtrl($scope) { 
    $scope.alerts = [ 
    { type: 'error', msg: 'Oh snap! Change a few things up and try submitting again.' }, 
    { type: 'success', msg: 'Well done! You successfully read this important alert message.' } 
    ]; 

    $scope.addAlert = function() { 
    $scope.alerts.push({msg: "Another alert!"}); 
    }; 

    $scope.closeAlert = function(index) { 
    $scope.alerts.splice(index, 1); 
    };  
} 
</script> 

這樣的話,你只需要添加的<alert>指令你的看法,你是好去 - 不需要創建共享服務或類似的東西。

+0

如果您不想添加整個UI Bootstrap項目依賴項,則至少可以使用相同的設計並編寫自己的指令。 –

+1

AlertDemoCtrl應該是rootController,否則它將不能用於另一個控制器,或者您將不得不將$ scope.alerts和所有這些功能複製到每個控制器 –