zoukankan      html  css  js  c++  java
  • angular js一factory,service,provider创建服务

    服务:在AngularJS 中,服务是一个函数或对象

    在写控制器的时候,不要复用controller,当我们的controller里面有相同的代码时,此时需要把它抽取成一个服务,所有的服务都符合依赖注入的原则,服务在整个应用的生命周期中存在,可用来共享数据。

    Angular提供了3种方法来创建服务,factory,service,provider

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
    </head>
    <body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <input type="text" ng-model="name"/> {{name}}
    </div>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        var app=angular.module("myApp",[]);
        //自定义服务provider,myService1为服务名
        app.provider('myService1', function () {
            this.$get = function () {
                return{
                    message: 'customprovider Message'
                }
            }
        });
        //自定义服务service
        app.service('myService2', function () {
            return ['上海'];
        });
        //自定义工厂factory
        app.factory("myService3", [function () {
            return [1, 2, 3, 4, 5, 6];
        }]);
    //service和factory类似,但返回的东西必须是对象
    app.controller(
    'myCtrl',function($scope,myService1,myService2,myService3){ $scope.name = '橘子'; console.log(myService1); console.log(myService2); console.log(myService3); }); </script> </body> </html>

    效果截图

    共享数据

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
    </head>
    <body>
    <div ng-app="myApp">
        <div ng-controller="firstCtrl">
            <input type="text" ng-model="data.name"/>
            <input type="text" ng-model="Data.message"/>
            <p>first{{data.name}}</p>
            <p>first{{Data.message}}</p>
        </div>
        <div ng-controller="secondCtrl">
            <p>second{{data.name}}</p>
            <p>second{{Data.message}}</p>
        </div>
    </div>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        var app = angular.module("myApp",[]);
        app.factory('Data',function(){
            return{
                message:'共享的数据'
            }
        });
        app.controller('firstCtrl',function($scope,Data){
            $scope.data ={
                name: '橘子'
            };
            $scope.Data = Data;
        });
        app.controller('secondCtrl',function($scope,Data){
            $scope.Data = Data;
        });
    </script>
    </body>
    </html>
  • 相关阅读:
    实例讲解虚拟机3种网络模式(桥接、nat、Host-only)
    期刊搜索问题——SCI、EI、IEEE和中文期刊
    面向对象分析与设计(C++)课堂笔记
    windows与VMware ubuntu虚拟机实现文件共享
    GDI+在绘制验证码中的使用
    【转】.net中快捷键的使用
    MD5加密“破解”在.NET平台实现最基本的理解
    UE4 Persona 骨架网格物体动画
    从零开始做3D地图编辑器 基于QT与OGRE
    TBB(Intel Threading Building Blocks)学习笔记
  • 原文地址:https://www.cnblogs.com/Tiboo/p/6757530.html
Copyright © 2011-2022 走看看