Angular js 初始

来源:互联网 发布:淘宝怎么装修模板 编辑:程序博客网 时间:2024/04/30 20:05

1. ng-app

data-ng-app

全文只有一个,告诉anjular 从哪个部分开始,入口。

2. ng-controller

控制器

3. ng-model

绑定输入域到控制器的属性

<div ng-app="myApp" ng-controller="myCtrl">    名: <input type="text" ng-model="firstName"><br>    姓: <input type="text" ng-model="lastName"><br>    <br>    姓名: {{firstName + " " + lastName}}</div><script>    var app = angular.module('myApp', []);    app.controller('myCtrl', function($scope) {        $scope.firstName = "John";        $scope.lastName = "Doe";    });</script>

4. ng-class 给div或其它元素 赋值

(1)
<p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>        <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>        <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>        <input type="checkbox" ng-model="error"> error (apply "red" class)
    当 deleted被选中时,添加 strike class,    当 important被选中时,添加 bold class等等(2)
<p ng-class="style">Using String Syntax</p>        <input type="text" ng-model="style" placeholder="Type: bold strike red">
    输入框输入的类型是多少,p段落则添加什么class(3) 
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>        <input ng-model="style1" placeholder="Type: bold, strike or red"><br>        <input ng-model="style2" placeholder="Type: bold, strike or red"><br>        <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
    同理得上,只是这多了样式和输入框

5. angular.module 是angular 代码的入口,加载模块,必须首先需要声明 module,才能定义angular 其它信息,例如指令啥的

三个参数:

  1.必须,模块定义的名称  ng-app 定义的名称  2.可选,模块的依赖,声明本模块需要依赖的其他模块的参数  3.可选,模块启动的配置函数一个参数:模块名称

6. .config配置服务啥的,使用于module 只有一个参数的情况下

//配置使用国际化服务
.config(['$translateProvider', function($translateProvider){    $translateProvider.useStaticFilesLoader({      prefix: 'l10n/',      suffix: '.js'    });    $translateProvider.preferredLanguage('en');    $translateProvider.useLocalStorage();  }]);

//按需加载模块

.config([‘ocLazyLoadProvider,function(ocLazyLoadProvider)

//加载路由机制

   .config(    [          '$stateProvider', '$urlRouterProvider',      function ($stateProvider,   $urlRouterProvider) {          $urlRouterProvider              .otherwise('/app/dashboard-v1');          $stateProvider              .state('app', {                  abstract: true,                  url: '/app',                  templateUrl: 'tpl/app.html'              })              .state('app.dashboard-v1', {                  url: '/dashboard-v1',                  templateUrl: 'tpl/app_dashboard_v1.html',                  resolve: {                    deps: ['$ocLazyLoad',                      function( $ocLazyLoad ){                        return $ocLazyLoad.load(['js/controllers/chart.js']);                    }]                  }              })              .state('app.dashboard-v2', {                  url: '/dashboard-v2',                  templateUrl: 'tpl/app_dashboard_v2.html',                  resolve: {                    deps: ['$ocLazyLoad',                      function( $ocLazyLoad ){                        return $ocLazyLoad.load(['js/controllers/chart.js']);                    }]                  }              })            }    ]    )

7. run方法 初始化全局数据,只对全局作用域起作用

.run(    [   '$rootScope', '$state', '$stateParams',      function ($rootScope,   $state,   $stateParams) {          $rootScope.$state = $state;          $rootScope.$stateParams = $stateParams;              }    ]    )

8. forEach 循环取数组

var jsonlist = { name :'mis',gr:'male'};    anjular.forEach(jsonlist,function(value ,key){    this.push(key + ':' + value);    },log)

9. ng-click 绑定事件

10. ng-init 初始应用时创建变量;执行给定的表达式;

11. ng-repeat 循环取数据,输出一个表格

<table ng-controller="myCtrl" border="1">        <tr ng-repeat="(x,y) in records">            <td>{{x}}</td>            <td>{{y}}</td>         </tr>    </table>
<script>    var app = angular.module("myApp", []);    app.controller("myCtrl", function($scope) {    $scope.records = [       {            "Name" : "Alfreds Futterkiste",            "Country" : "Germany"        },{            "Name" : "Berglunds snabbk?p",            "Country" : "Sweden"        },{            "Name" : "Centro comercial Moctezuma",            "Country" : "Mexico"        },{            "Name" : "Ernst Handel",            "Country" : "Austria"        }    ]    });    </script>

12. ng-show

主要应用于 CSS3 的动画效果(1)过渡效果:
 transition 从属性值过渡到另一个值中                 transition: width/all/opacity 1s linear 2s;                 -moz-transition:width/all/opacity 1s linear 2s;                 -webkit-transition:width/all/opacity 1s linear 2s;                 -o-transition:width/all/opacity 1s linear 2s;
(2)动画效果:
 @keyframes            先规定动画名称及动画效果,注意火狐谷歌的样式                @keyframes myfirst{                    0% {background: red; left:0px; top:0px;}                    25%  {background: yellow; left:200px; top:0px;}                    50%  {background: blue; left:200px; top:200px;}                    75%  {background: green; left:0px; top:200px;}                    100% {background: red; left:0px; top:0px;}                    }
        再把动画应用到相应的div上
div{                    animation: myfirst 5s linear 2s infinite alternate;                    -moz-animation: myfirst 5s linear 2s infinite alternate;                    -webkit-animation: myfirst 5s linear 2s infinite alternate;                    -o-animation: myfirst 5s linear 2s infinite alternate;                    }

13. 前端和后台的数据对接

前后端通信通过$http()服务实现,$http服务只能接受一个参数的函数,这个参数是一个对象,包含了用来生成HTTP请求的配置内容。这个函数返回一个promise对象,具有success和error两个方法。例如 http  采用GET 方式获取: 
$http({        method: 'GET',        url: '/api/users.json'    }).success(function(data,status,headers,config) {        // 当相应准备就绪时调用    }).error(function(data,status,headers,config) {        // 当响应以错误状态返回时调用    });
以下为  POST 方式
this.getInviteData=function (pageNum,pageSize,sort,edition) {        $http({            method:'POST',            url:'member_list.action',            data:JSON.stringify({                'pageNum': pageNum,                'pageSize': pageSize,                'sort': sort,                'edition': edition            })        }).success(function (data,status,header,config) {            if(data.status == 'true'&& data.recordList){                //每次请求,清空原数组内的数据,不然会出现数据累加,从而出现Bug                inviteData.data=[];                //遍历数据库里的recordList里的数据,record指的就是当前遍历的数据                angular.forEach(data.recordList,function (record) {                    //把record里的数据存储到 inviteData.data这个已经设置好的空数组里                    inviteData.data.push({                        name:record.name,                        department:record.department,                        position:record.position,                        phoneNumber:record.phoneNumber,                        state:record.state                    });                });                //总人数,将url请求的数据里的recordCount赋值给inviteData.total                inviteData.total=data.recordCount;                inviteData.hasJoinedPeople=data.joinCount;                //向子级$scope传递数据                $rootScope.$broadcast('getInviteDataA',inviteData);            }else if(data.status=='false'){                console.info('由于网络问题,暂时无法获取数据');            }        }).error(function (data,status,header,config) {            console.error('服务器繁忙,请稍后再试!');        });    };
以下介绍两种  数据格式转化的方法    1、JSON.parse()用于从一个字符串中解析出json对象。        var str = '{"name":"huangxiaojian","age":"23"}';        JSON.parse(str);//age: "23"   name: "huangxiaojian"    2、JSON.stringify()用于从一个对象解析出字符串。        var a = {a:1,b:2};        JSON.stringify(a);// "{"a":1,"b":2}"数据传递——$rootScope.$broadcast()

  每次请求成功,都需要把在service里的数据通过 rootScope.broadcast() 广播给其在controller里的 子级scopescope.$on()接收父级传来的数据)。