具有角JS UI通知 [英] UI Notifications with angular js

查看:73
本文介绍了具有角JS UI通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现具有角JS一些标准的通知UI。我的做法是以下(简体):

I have to implement some standard notification UI with angular js. My approach is the following (simplified):

<div ng-controller="MainCtrl">
  <div>{{message}}</div>
  <div ng-controller="PageCtrl">
     <div ng-click="showMessage()"></div>
  </div>
</div>

和与页面控制器存在:

module.controller("PageCtrl", function($scope){
  counter = 1
  $scope.showMessage = function(){
    $scope.$parent.message = "new message #" + counter++;
  };
});

这工作正常。但我真的不喜欢的事实,我需要调用$范围。$父。

This works fine. But I really don't like the fact that I need to call $scope.$parent.

因为如果我在另一个嵌套的控制器,我将有$范围。$的父母。父母$,这很快变成了一场噩梦理解。

Because if I am in another nested controller, I will have $scope.$parent.$parent, and this becomes quickly a nightmare to understand.

有另一种方式来创建这样的全球UI通知具有角?

Is there another way to create this kind of global UI notification with angular?

推荐答案

使用事件来发送消息从一个组件到另一个。这样的组件不需要在所有相关

Use events to send messages from one component to another. That way the components don't need to be related at all.

从一个组件发送事件:

app.controller('DivCtrl', function($scope, $rootScope) {
  $scope.doSend = function(){
    $rootScope.$broadcast('divButton:clicked', 'hello world via event');
  }
});

和创建监听任何你喜欢的,如在另一个组件:

and create a listener anywhere you like, e.g. in another component:

app.controller('MainCtrl', function($scope, $rootScope) {
  $scope.$on('divButton:clicked', function(event, message){
    alert(message);
  })
});

我在<创建的工作示例为你href=\"http://plnkr.co/edit/ywnwWXQtkKOCYNeMf0FJ?p=$p$pview\">http://plnkr.co/edit/ywnwWXQtkKOCYNeMf0FJ?p=$p$pview

您还可以查看 AngularJS文档有关范围阅读更多关于实际的语法。

You can also check the AngularJS docs about scopes to read more about the actual syntax.

此为您提供在code的短短几行干净,快速的解决方案。

This provides you with a clean and fast solution in just a few lines of code.

问候,
尤尔根

Regards, Jurgen

这篇关于具有角JS UI通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆