zoukankan      html  css  js  c++  java
  • 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

    
    
  • 相关阅读:
    setoptsocket函数
    C++右值引用
    const char* char const* char*const
    select()函数以及FD_ZERO、FD_SET、FD_CLR、FD_ISSET
    gitee搭建应用
    C++ 实现基本运算+-*/
    C++学习笔记(一)mutable function
    创造型设计模式-----抽象工厂模式
    openPhase gcc迁移
    SQLPLUS 远程连接数据库
  • 原文地址:https://www.cnblogs.com/dianzan/p/7284320.html
Copyright © 2011-2022 走看看