[AngularJS] Using Services in Angular Directives

Directives have dependencies too, and you can use dependency injection to provide services for your directives to use.

Bad: If you want to use <alert> in another controller or page, you have to modify the AlertService. This might break things.

<!DOCTYPE html>
<html>
<head>
    <title>Egghead.io Tutorials</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="app" ng-controller="MainCtrl as main">

    <alert type="{{main.AlertService.alertType}}" ng-if="main.AlertService.isShowAlert">{{main.AlertService.alertMessage}}</alert>
    <button ng-click="main.showAlert();">Something Failed</button>
</body>
</html>
angular.module("app", ["ui.bootstrap"])
    .controller(‘MainCtrl‘, function MainCtrl(AlertService) {
        var mainCtrl = this;
        mainCtrl.AlertService = AlertService;
    })

    .service(‘AlertService‘, function AlertService() {
        var AlertService = {};
        AlertService.false = true;
        AlertService.showAlert = function() {
            AlertService.alertType="success";
            AlertService.alertMessage = "There is a message";
            AlertService.isShowAlert = true;
        }
        return AlertService;
    });

Good: Using Directive injected by the service. Then the <alert> is no longer bind with the controller anymore.

<!DOCTYPE html>
<html>
<head>
    <title>Egghead.io Tutorials</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="app" ng-controller="MainCtrl as main">

    <alert-message></alert-message>
    <!--<alert type="{{main.AlertService.alertType}}" ng-if="main.AlertService.isShowAlert">{{main.AlertService.alertMessage}}</alert>-->
    <button ng-click="main.showAlert();">Something Failed</button>
</body>
</html>
angular.module("app", ["ui.bootstrap"])
    .service(‘AlertService‘, function AlertService() {
        var AlertService = {};
        AlertService.false = true;
        AlertService.showAlert = function() {
            AlertService.alertType="success";
            AlertService.alertMessage = "There is a message";
            AlertService.isShowAlert = true;
        }
        return AlertService;
    })

    .directive(‘alertMessage‘, function() {
        return {
            bindToController: true,
            controller: ‘AlertCtrl‘,
            controllerAs: ‘alertCtrl‘,
            template: ‘<alert type="{{alertCtrl.AlertService.alertType}}" ng-if="alertCtrl.AlertService.isShowAlert">{{alertCtrl.AlertService.alertMessage}}</alert>‘
        }
    })

    .controller(‘AlertCtrl‘, function(AlertService) {
        var alertCtrl = this;

        alertCtrl.AlertService = AlertService;
    })

    .controller(‘MainCtrl‘, function(AlertService) {
        var main = this;
        main.AlertService = AlertService;
        main.showAlert = function() {
            main.AlertService.isShowAlert = true;
            main.AlertService.alertType="danger";
            main.AlertService.alertMessage = "Something wrong happened";
        }
    });

anuglar-ui-bootstrap:

http://angular-ui.github.io/bootstrap/

bindToController:

http://flipjs.io/2014/09/09/isolate-scope-controller-as/

时间: 2024-08-08 01:25:30

[AngularJS] Using Services in Angular Directives的相关文章

[AngularJS] Accessing Services from Console

Using the Chrome console, you can access your AngularJS injectable services. This is down and dirty debugging, and can be a lifesaver in troubling times. You can get services/factories in console by using: var $injector = angular.element($0).injector

AngularJS 之Services讲解

Angular带来了很多类型的services.每个都会它自己不同的使用场景.我们将在本节来阐述. 首先我们必须记在心里的是所有的services都是singleton(单例)的,这也是我们所希望得到的预期结果. 下面让我开始今天的services之旅吧: Constant 示例: app.constant('fooConfig', { config1: true, config2: "Default config2" }); constant是个很有用的东东,我们经常会用于对dire

AngularJS的核心对象angular上的方法全面解析(AngularJS全局API)

总结一下AngularJS的核心对象angular上的方法,也帮助自己学习一下平时工作中没怎么用到的方法,看能不能提高开发效率.我当前使用的Angularjs版本是1.5.5也是目前最新的稳定版本,不过在全局API上,版本不同也没什么区别. AngularJS 全局 API列表 element bootstrap copy extend merge equals forEach noop bind toJson fromJson identity isUndefined isDefined is

[AngularJS] Consistency between ui-router states and Angular directives

ui-router's states and AngularJS directives have much in common. Let's explores the similarities between the two and how these patterns have emerged in Angular. Keeping your states and directives consistent can also help with refactoring as your app

[Angular Directive] Combine HostBinding with Services in Angular 2 Directives

You can change behaviors of element and @Component properties based on services using @HostBinding in @Directives. This allows you to build @Directives which rely on services to change behavior without the @Component ever needing to know that the Ser

[AngularJS] Hijacking Existing HTML Attributes with Angular Directives

Angular overrides quite a few existing HTML elements and attributes. This can be a useful technique in our own applications. We will build a directive that adds additional functionality to the src property of an <img>. Javascript: /** * Created by A

在AngularJS中何时应该使用Directives,Controllers或者Service

原文: http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/ Services Service是单例的. 可以让你在你应用的不同代码块中共享同一个数据. 首先定义一个module. var module = angular.module( "my.new.module", [] ); 接下来, 创建一个service名为Book, 其中有一个json对象包含了一些图书的数据. m

angularJs中筛选功能-angular.filter-1

技术分享:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/angular-filter-learn-1/ 以下介绍为自己在使用angular-filter时,简单总结的用法. 开始 1.你可以使用4中不同的方法来安装angular-filter: 克隆或创建这个存储库 通过bower:通过在你的终端执行:$ bower install angular-filter 通过npm:通过在你的终端执行:$ npm install an

AngularJs学习笔记--Understanding Angular Templates

原版地址:http://docs.angularjs.org/guide/dev_guide.mvc.understanding_model angular template是一个声明规范,与model.controller的信息一起,渲染成用户在浏览器中所看到的视图.它是静态的DOM,包括HTML.CSS.angular特别的元素和angular指定的元素属性.angular元素和属性指示angular去扩展行为以及将template DOM转换为动态视图的DOM. 下面是我们可以在templ