AngularJs 笔记

初识

directive 指令

  1. ng-app 初始化一个AngularJs应用程序(经过一个值(好比 ng-app="myModule")链接到代码模块。)
  2. ng-init 初始化应用程序数据(通常不用)
  3. ng-model 把元素值绑定到应用程序(mvvm的双向绑定)
  4. ng-bind 将应用程序数据绑定到html视图
  5. 表达式 {{}} 功能相似 ng-bind,但更普遍的用途html

    <!DOCTYPE html>
     <html lang="zh-cn">
     <head>
     <meta charset="utf-8">
     <script src="angular.min.js"></script> 
     </head>
     <body>
     <div ng-app="" ng-init="firstName='John'">
    
     <p>在输入框中尝试输入:</p>
     <p>姓名: <input type="text" ng-model="firstName"></p>
     <p>你输入的为: {{ firstName }}</p>
     <p>你输入的为: <span ng-bind="firstName"></span></p>
     </div>
     </body>
     </html>
  6. ng-repeat 重复一个html元素(循环)
  7. 自定义指令json

    mainApp.directive('focus', function () {
        return {
          link: function (scope, element, attrs) {
            element[0].focus();
          }
        };
      });
  8. 其余经常使用指令
    ng-show,ng-hide,ng-class,ng-view,ng-switch, ng-if, ng-options,ng-disabled,ng-click,ng-include="''"(须要引号,跨域要设置白名单)api

表单验证

状态信息

<form ng-app="" name="myForm">
        Email:
        <input type="email" name="myAddress" ng-model="text">
        <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
    </form>

    <p>提示信息会在 ng-show 属性返回 true 的状况下显示。</p>

样式切换

ng-model 指令根据表单域的状态添加/移除如下类跨域

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine

做用域scope

$scope.$watch('passw1',function() {$scope.test();});数组

过滤器filter

  1. uppercase,lowercase 大小写转换浏览器

    {{ "lower cap string" | uppercase }}   // 结果:LOWER CAP STRING
     {{ "TANK is GOOD" | lowercase }}      // 结果:tank is good
  2. date 格式化服务器

    {{1490161945000 | date:"yyyy-MM-dd HH:mm:ss"}} // 2017-03-22 13:52:25
  3. number 格式化(保留小数)app

    {{149016.1945000 | number:2}}
  4. currency货币格式化mvvm

    {{ 250 | currency }}            // 结果:$250.00
     {{ 250 | currency:"RMB ¥ " }}  // 结果:RMB ¥ 250.00
  5. limitTo 截取ide

    {{"1234567890" | limitTo :6}} // 从前面开始截取6位
     {{"1234567890" | limitTo:-4}} // 从后面开始截取4位
  6. 查找、排序、自定义过滤

    <body ng-app="myApp">
     <div ng-controller="myCtrl">
         <div ng-bind="myName  | uppercase"></div> <!--uppercase转换成大写-->
         <div class="" ng-bind="money | currency : '¥'"> </div><!--currency 过滤器将数字格式化为货币格式-->
         <div class="" ng-repeat="v in city | orderBy:'id'">
             <p ng-bind="v.name"></p>
         </div><!--orderBy 过滤器根据表达式排列数组-->
    
         <div class="" ng-repeat="v in city | orderBy:'-id' | filter : '上海'">
             <p ng-bind="v.name" style="color:red;"></p>
         </div>
         <!--orderBy 过滤器根据表达式排列数组   默认正序asc,倒序添加-负号-->
         <!--filter 过滤器根据表达式过滤不包含过滤器中的内容-->
    
         <!--自定义过滤器aa-->
         <div class="" ng-bind="myName | reverse" style="color:blue;"></div> 
         <div class="" ng-bind="myName | reverse:true" style="color:blue;"></div>            
     </div>
     <script>
     angular.module('myApp',[]).controller('myCtrl',function($scope){
         $scope.myName="Dhx";
         $scope.money=100;
         $scope.city=[
             {"id":"1","name":"福建"},
             {"id":"2","name":"广东"},
             {"id":"5","name":"上海"},
             {"id":"4","name":"北京"},
             {"id":"3","name":"四川"}
         ]
     }).filter('reverse',function(){ 
         return function(input, uppercase){
                          input = input || '';
                          var out = input.split("").reverse().join("");
                          if (uppercase) {
                          out = out.toUpperCase();
                          }
              return out;
         }
     })
     </script>
     </body>

服务Service

$location ,$http(不能跨域) , $timeout, $interval

用provider自定义一个服务

(1)

var mainApp = angular.module('mainApp', []);
mainApp.config(function($provide) {
    $provide.provider('CalcService', function() {
    this.$get = function() {
        var factory = {};  
     
        factory.square = function(a) {
            return a * a; 
        }
        return factory;
    };
    });
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(2)

var mainApp = angular.module('mainApp', []);
mainApp.config(function($provide) {
    $provide.factory('CalcService', function() {
            var factory = {};  
     
            factory.square = function(a) {
                return a * a; 
            }
            return factory;
    });
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(3)

var mainApp = angular.module('mainApp', []);
mainApp.config(function($provide) {
    $provide.factory('CalcService', function() {
        return function(a) {
            return a * a; 
        };
    });
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService($scope.number);
    }
 });

用factory自定义一个服务

(1)

var mainApp = angular.module('mainApp', []);
mainApp.factory('CalcService', function() {
    var factory ={};
    factory.square = function(a) {
        return a * a; 
    }
    return factory;
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(2)

var mainApp = angular.module('mainApp', []);
mainApp.factory('CalcService', function() {
        return function(a) {
            return a * a; 
        }
    });

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService($scope.number);
    }
 });

用service自定义一个服务

(1)

var mainApp = angular.module('mainApp', []);
mainApp.service('CalcService', function(){
    this.square = function(a) {
        return a * a; 
    }
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService.square($scope.number);
    }
 });

(2)

var mainApp = angular.module('mainApp', []);
mainApp.service('CalcService', function(){
    return function(a) {
        return a * a; 
    }
});

mainApp.controller('MainCtrl', function ($scope,CalcService) {  
    $scope.square = function() {
        $scope.result = CalcService($scope.number);
    }
 });

依赖注入

value,factory,service,provider,constant

select


Api

  • angular.lowercase(a) 转换字符串为小写
  • angular.uppercase(a) 转换字符串为大写
  • angular.isString(a) 判断给定的对象是否为字符串,若是是返回 true。
  • angular.isNumber(a) 判断给定的对象是否为数字,若是是返回 true。
  • angular.isFunction(a)
  • angular.extend(a,b) 从b对象复制全部属性和函数到a.
  • angular.copy(a),angular(a,b) 拷贝一个副本
  • angular.isObject(a)
  • angular.isArray(a)
  • angular.forEach(object,function(value,key){}); angular.forEach(myArray,function(value,index){})
  • angular.isDefined(a)
  • angular.isUndefined(a)

路由

http://runoob.com/#/first
http://runoob.com/#/second

对服务器而言它们是同一个连接,AngularJS路由就经过“ # + 标记”帮助咱们区分不一样的逻辑页面并将不一样的页面绑定到对应的控制器上。

  1. 载入了实现路由的 js 文件:angular-route.js。
  2. 包含了 ngRoute 模块做为主应用模块的依赖模块。

    angular.module('routingDemoApp',['ngRoute'])
  3. 使用 ngView 指令。

    <div ng-view></div>//该 div 内的 HTML 内容会根据路由的变化而变化。
  4. 配置 $routeProvider,AngularJS $routeProvider 用来定义路由规则。

    module.config(['$routeProvider', function($routeProvider){
         $routeProvider
             .when('/',{template:'这是首页页面'})
             .when('/computers',{template:'这是电脑分类页面'})
             .when('/printers',{template:'这是打印机页面'})
             .otherwise({redirectTo:'/'});
     }]);

$routeProvider.when

$routeProvider.when(url, {
    template: string,
    templateUrl: string,
    controller: string, function 或 array,
    controllerAs: string,
    redirectTo: string, function,
    resolve: object<key, function>
});
  • template:若是咱们只须要在 ng-view 中插入简单的 HTML 内容,则使用该参数:
  • templateUrl: 若是咱们只须要在 ng-view 中插入 HTML 模板文件,则使用该参数:

    $routeProvider.when('/computers', {
    templateUrl: 'views/computers.html',
    });

  • controller: function、string或数组类型,在当前模板上执行的controller函数,生成新的scope。
  • controllerAs: string类型,为controller指定别名。
  • redirectTo: 重定向的地址。
  • resolve: 指定当前controller所依赖的其余模块。

猜想(待确认):

  1. 一个应用能够有多个模块,但在页面上只能有一个ng-app指令,一个模块能够有多个controller
  2. 若是html是视图,JavaScript代码中应该有一个自动构建的对应的viewModel
  3. 每一个controller对应着一个scope。controller与controller之间相关隔离,经过rootScope共享数据。
    经过在controller中修改scope,也就在修改viewModel,进而也就修改了view,由于view和viewModel是自动同步的,
  4. $XX表明这是一个应用对象,如$scope, $rootScope,$valid,$dirty,$touched,$error等, $符号不能缺失

笔记 (待整理)

  1. var todoApp = angular.module("todoApp",[]);其中第二个参数是一个由所依赖模块构成的数组,换言之在应用中是能够存在多个模块的。
    1. var todoApp = angular.module("todoApp");则是查找已定义的模块todoApp
  2. 浏览器插件batarang
  3. todoApp.run(function($http){$http.get("todo.json").then(function(data){model.items=data;})});run方法会在AngularJs执行完初始化设置后容许一次。
  4. AngularJs自带一个裁剪版的jQuery,叫作jqLite,而若是页面中引入了jQuery,AngularJs会自动检测到并优先使用jQuery代替jqLite。
  5. 规则
    1. 视图逻辑仅为显示准备数据,永远不该该修改模型。
    2. 控制器逻辑永远都不该该直接增删改模型中的数据。
    3. 客户端永远都不该该直接访问数据存储。
  6. JS中的对象操做

    var myData = {name:"name",weather:"weather"};
     //判别类型
     console.log(angular.isObject(myData)) //true
     //遍历
     angular.forEach(myData, function(value,key){
         console.log("name:"+key+", value:"+value);
     });
    
     //扩展
     var myExtendObject = {city:"london"};
     angular.extend(myExtendObject,myData);
     console.log(myExtendObject.weather);
     //复制
     var dataCopy = angular.copy(myData);
     console.log(dataCopy.weather);
     //删除属性或方法
     delete myData.name;
     console.log(myData.name) // undefined
     //判别是否拥有属性
     var hasName = "name" in myData;
     console.log(hasName) // false
     console.log("weather" in myData)//true
相关文章
相关标签/搜索