zoukankan      html  css  js  c++  java
  • angular(3)服务 --注入---自定义模块--单页面应用

    ng内部,一旦发生值改变操作,如$scope.m=x,就会自动轮询$digest队列,触发指定的$watch,调用其回调函数,然后修改dom树。

    干货:https://github.com/xufei/blog/issues/10

    1.ng提供了许多内置的服务,例如常用的$scope$http$window$location等。

    http:POST请求:

    var app = angular.module('myApp', ['ng']);
        app.run(function($http){           //post 请求设置请求头
            $http.defaults.headers.post = {'Content-Type':'application/x-www-form-urlencoded'};
        });
        app.controller('ctl', function ($scope,$http) {
            var obj={"name":"xiaode","age":16};
    
            $scope.sendData=function () {
                console.log($.param(obj));
                $http.post('server.php',$.param(obj)).success(function (data) {
                    $scope.data=data
                })
            }
        })
    GET请求类似不需要设置请求头


    自定义服务

    factory自定义服务:app.factory(name,fn)  fn为一个函数返回对象

    service自定义服务:app.factory(name,fn)  fn为一个构造函数

    constant、value自定义服务 类似不过第二个参数是一个对象

    demo:

    <script>
        var app = angular.module('myApp', ['ng']);
        /*自定义服务*/
        app.factory('$output',function () { //对象形式 factory
            return{
                print:function (msg) {
                  console.log(msg);
                }
            }
        });
        app.service('$student',function () { //构造函数的形式
            this.name='Mical';
            this.speak=function () {
                console.log(this.name);
            }
        });
        app.controller('ctl', function ($scope,$output,$student) {
            $output.print('ddsd');
            console.log($student.name);
        })
    <script>

    2.  三种写法:推断式  标记式    行内式   ,下面demo只是写出 注入服务的形式

    var app = angular.module('myApp', ['ng']);
        app.factory('$show', function () {
            return {
                show: function () {
                    alert("hello  factory show");
                }
            }
        });
        app.service('$print', function () {
            this.print = function () {
                alert('hello serverce print');
            }
        });
        app.controller('ctl1', function ($scope, $print, $show) {
            //推断式注入不需要关注参数的先后顺序 ng会推断这个服务是否存在
            //不能处理压缩和混淆后的代码,只能处理原始代码
        });
        var ctrFunc = function ($scope, $show, $write) {
        };
        ctrFunc.$inject = ['$scope', '$show', '$write'];    //标记式依赖注入不能是匿名函数
        app.controller('ctl2', ctrFunc);
        app.controller('ctl3', ['$scope', '$print', '$show', function ($scope, $print, $show) {
            //行内式,最优写法
        }])
    </script>

    3.ps:手动可以通过 var jector=angular.injector([‘ng’,‘myApp’])得到注入器  然后has(‘’)判断  在get(‘’)


    4.自定义模块:

    <script>
        var app01 = angular.module('myApp01', ['ng']);
        app01.factory('$custom',function () {
            return {
                show:function () {
                    console.log('自定义模块');
                }
            }
        });
        app02=angular.module('myApp02',['ng','myApp01']);
        app02.controller('ctl', ['$scope','$custom',function($scope,$custom) {
            $scope.print=function () {
                $custom.show();
            }
        }])
    </script>

    5.单页面应用(SPA)

    异步请求,通过路由确定资源,局部更新

    步骤:

    1.创建唯一完整的页面:index.html,引入angular.js和angular-route.js
    2.创建自定义模块,声明依赖于ng和ngRoute两个模块
    3.在index.html的body中使用ngView指令声明一个容器元素,用于盛放模板页面
    4.创建模板页面
    5.在当前模块中使用ngRoute提供的对象配置路由字典
    6.创建几个模板页面
    7.测试路由字典的配置是否正确 http://127.0.0.1/index.html#/路由地址

    上demo:

    首先是html片段

    main.html

    <div ng-include="'tpl/header.html'"  ></div>  //引入头部html片段 
    <h1>主页</h1>
    <button ng-click="jump('/Person/3')">跳转到person</button>   //3是传入到person的参数  
    <div ng-include="'tpl/footer.html'"></div>

    person.html

    <div ng-include="'tpl/header.html'"></div>
    <h1>个人中心</h1>
    <a ng-click="jump('/Main')">跳转到主页</a>
    <div ng-include="'tpl/footer.html'"></div>

    index.html

    <!DOCTYPE html>
    <html lang="en" ng-app="myApp">
    <head>
        <meta charset="UTF-8">
        <title>Angular</title>
        <script src="js/angular.js"></script>
        <script src="js/angular-route.js"></script>
    </head>
    <body ng-controller="parentCtrl">
        <div ng-view></div>
    <script>
        var app = angular.module('myApp',['ng','ngRoute']);
        app.controller('parentCtrl',['$scope','$location',function ($scope,$location) {//需要$location服务
            $scope.jump=function (arg) {   //在body控制器中定义jump(),在子$scope里面都可以用
                $location.path(arg)
            }
        }]);
       app.config(function ($routeProvider) {  //路由配置
           $routeProvider.when('/Person',{
                templateUrl:'tpl/person.html'
            }).when('/Main',{
                templateUrl:'tpl/main.html'
            }).when('/Person/:id',{   //接收方接收参数 参数名ID
                templateUrl:'tpl/person.html',
                controller:'personCtrl'
            }).otherwise({
                redirectTo:'/Main'
            })
        });
        app.controller('personCtrl',['$scope','$routeParams',function ($scope,$routeParams) {
            console.log($routeParams.id);   //如果需要传参数,就需要$scopeParms服务 
        }]);
    </script>
    </body>
    </html>
  • 相关阅读:
    94. Binary Tree Inorder Traversal
    101. Symmetric Tree
    38. Count and Say
    28. Implement strStr()
    实训团队心得(1)
    探索性测试入门
    LC.278. First Bad Version
    Search in Unknown Sized Sorted Array
    LC.88. Merge Sorted Array
    LC.283.Move Zeroes
  • 原文地址:https://www.cnblogs.com/godbutton/p/6119613.html
Copyright © 2011-2022 走看看