• Angular injector注入器


    <!DOCTYPE html>
    <html ng-app="myApp">
    <head lang="en">
    <meta charset="UTF-8">
    <script src="js/angular.js"></script>
    <title></title>
    </head>
    <body>
    <div ng-controller="myCtrl">

    </div>
    <script>
    var app = angular.module('myApp', ['ng']);
    //通过service方法创建自定义服务
    app.service('$test', function () {
    this.info = 'it is a test';
    })


    //得到注入器 个人理解为在此处继承了$text的服务
    var injector = angular.injector(['ng', 'myApp']);
    console.dir(injector);
    //手工判断该服务是否存在
    var result = injector.has('$test')
    console.log(result);
    //如果存在,得到该服务对象,调用属性或者方法
    if (result) {
    var testObj = injector.get('$test');
    console.log(testObj.info);
    }

    //采用行内式依赖注入
    app.controller('myCtrl',
    ['$scope','$injector' ,
    function ($scope,$injector ) {
    if($injector.has('$test'))
    {
    var result = $injector.get('$test').info;
    // 或者var result = testObj.info;
    console.log("in myCtrl is "+ result)
    }
    }])
    </script>
    </body>
    </html>

    invoke()

    使用注入器的invoke()方法,可以直接调用一个用户自定义的函数体,并通过函数参数 注入所依赖的服务对象,这是AngularJS推荐和惯例的用法:

    angular.injector(['ng'])

    .invoke(function($http){

    //do sth. with $http

    });

    get()

    也可以使用注入器的get()方法,获得指定名称的服务实例:

    varmy$http=angular.injector(['ng']).get('$http');

    //do sth. with my$http

    
    
  • 相关阅读:
    JDK Base64编解码1.7和1.8的坑
    nacos部署注意点
    详解CurrentHashMap之预习篇
    SpringBoot爬坑系列
    开发之缓存与数据库优化
    jreble备注
    Unable to open debugger port (127.0.0.1:55119): java.net.SocketException "Socket closed"
    ConcurrentHashMap源码分析
    为什么要先高16位异或低16位再取模运算
    HashMap(三)之源码分析
  • 原文地址:https://www.cnblogs.com/dianzan/p/7284320.html
Copyright © 2020-2023  润新知