AngularJS线人服务 [英] AngularJS Informer service

查看:208
本文介绍了AngularJS线人服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Twitter的引导在我的Web应用程序的用户界面。格外其警报组件。我想写一个简单的角度服务来包装引导的警示有从角code的任何和平告知用户的可能性。像这样的:

I'm using Twitter Bootstrap for UI in my webapp. Particulary its Alert component. I want to write a simple angular service to wrap Bootstrap's Alert to have a possibility of informing users from any peace of angular code. Like this:

Informer.inform("message", "ERROR"); // will result in alerting with `alert-error` class
Informer.inform("message", "INFO"); // will result in alerting with `alert-info` class

我的想法是到模板追加到年底的<身体GT;

<div class="alert {{alertClass}} fade in informer" id="informer">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <div class="valignCenterWrapper">
        <div class="valignCenter" id="informerMessage">
            {{message}}
        </div>
    </div>
</div>

事情是这样的:

grfx.factory("Informer", function() {
    return {
        inform : function(message, type) {
            // Here be dragons. How can I compile/append the template.

            $("#inform").alert();
        }
    };
});

我想知道的唯一一件事:我怎么写这个具有角,不使用jQuery?是code以上好的开始?在互联网络乡亲们说,我应该的使用指令的DOM操作。但我不明白:我没有任何现有的标记在其应用指令。警报将被追加到网页,因为一些compupations /用户交互的结果。哪些服务( $编译 $解析 $文件 )我应该使用编译temlate某处其追加到身体?

The only thing I want to know: how do I write this with angular, not with jQuery? Is the code above good for start? Folks in the internets say that I should only use directives for DOM manipulation. But I do not understand it: I do not have any existing markup to apply directive on it. Alerts will be appended to the page as a result of some compupations/user interactions. Which services ($compile, $parse, $document) should I use to compile temlate and append it somewhere to the body?

修改:是否也可以得到控制外angularjs服务。就在常规JS code,所以我可以写 getServiece(线人)。通知(,)

EDIT: Is it also possible to get angularjs service outside of controller. Just in regular JS code so I can write getServiece("Informer").inform("", "")?

编辑2 :好吧,我现在有:

grfx.factory("Informer", function($compile, $rootScope) {
    return {
        inform : function(message, type) {
            var scope = $rootScope.$new();

            scope.message = message;
            scope.type = type;

            $(document.body).append($compile("<div class='alert {{type}} fade in informer' id='informer'><button type='button' class='close' data-dismiss='alert'>×</button><div class='valignCenterWrapper'><div class='valignCenter' id='informerMessage'>{{message}}</div></div></div>")(scope));
        }
    };
});

有了这个code我能使用注射服务从控制器。但有一个问题,当我尝试调用外角code服务:

With this code I am able to use injected service from controllers. But there is an issue when I try to call service outside angular code:

angular.element(document).injector().get("Informer").inform("Message", "alert-error");

这显示了 {{}信息} 例如弹出不正确编译模板。

This shows popup with {{message}} e.g. it does not compile template correctly.

推荐答案

在我们应该专注于模型操作,你的线人服务AngularJS也不例外 - 它仅应持有模式,不应与DOM操作有关。经验法则,其中DOM操作=指令是一个非常不错的,如果你按照它会为你节省很多麻烦。

In AngularJS we should be focusing on model manipulation and your Informer service is no exception - it should only hold model and shouldn't be concerned with DOM manipulation. The rule of thumb where DOM manipulation = directive is a very good one and if you follow it it will save you a lot of headaches.

回到手头的问题,解决的办法是有一个服务集中在模型操作和指令,显示这一模式。让我们先从服务:

Back to your problem at hand, the solution is to have a service focused on model manipulation and a directive to display this model. Let's start with the service:

app.factory('Informer', function(){

  var messages = [];  
  var Informer = {};

  Informer.inform = function(msg, type) {
    messages.push({
      msg: msg,
      type: type
    });
  };

  Informer.allInfos = function() {
    return messages;
  };

  Informer.remove = function(info) {
    messages.splice(messages.indexOf(info), 1);
  };  

  return Informer;
});

在此服务准备就绪您可以轻松地在控制器使用它(甚至里面等服务!)

When this service is ready you can easily use it in a controller (or even inside other services!):

app.controller('MainCtrl', function($scope, Informer) {

  Informer.inform("error message", "error");
  Informer.inform("info message", "info");

  $scope.allInfos = Informer.allInfos;  
  $scope.remove = Informer.remove;
});

最后,呈现提醒您可以直接使用引导的标记,或者写一个非常简单的指令,它封装。在这里我使用警报指令从 http://angular-ui.github.com/bootstrap/

<body ng-controller="MainCtrl">
    <alert ng-repeat="alert in allInfos()" type="alert.type" close="remove(alert)">{{alert.msg}}</alert>
  </body>

当然,你并不需要使用的指令从这个回购,你可以创建自己的或者如果需要使用原始标记。

Of course you don't need to use directives from this repo, you can create your own or use raw markup if needed.

下面是一个plunker展示工作示例:<一href=\"http://plnkr.co/edit/VxAcjHFhxXODFB5iAfyX?p=$p$pview\">http://plnkr.co/edit/VxAcjHFhxXODFB5iAfyX?p=$p$pview

Here is a plunker demonstrating a working example: http://plnkr.co/edit/VxAcjHFhxXODFB5iAfyX?p=preview

要总结一下:


  • 作为一个经验法则不做DOM操作指令之外

  • 服务处理的模式应该从模型的presentation脱钩

我也建议删除项目的jQuery,而学习的AngularJS。这样,您将更快地进入AngularJS禅境界!

I would also advice removing jQuery from a project while learning AngularJS. This way you will quicker get into AngularJS-zen state!

这篇关于AngularJS线人服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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