2013-06-28 99 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和所有这些功能复制到每个控制器 –