angular 一

  • 表單驗證 自定義驗證 errorjavascript

    express+angular

    新建一個 express 項目
express -e express_angular 
cd express_angular && sudo npm install -d
  • 修改ejs文件名為html
//app.js 
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html'); //替換文件擴展名ejs爲html
  • 修改views 文件下的index.ejs為index.html error.ejs 為error.html
  • 同時去掉文件裏面的<%= %>
  • 當然要添加angular.js 到index.html 中;

流浪貓の窩css

ng-model-options

控制ng-model什麼時候進行同步。

1.當某個肯定的事件被觸發的時候 2.在指定的防抖動延遲時間以後,這樣視圖值就會在指定的時間以後被同步到模型.html

ng-model-options="{updateOn:'blur'}"//失去焦點時同步,更新
ng-model-options="{debounce:1000}" //有一秒的延遲;

$watch

$scope.$watch(watchObj,watchCallBack,ifDeep)

watchObj 須要被檢測的對象,該對象多是 摸個數據,表達式,或者一個函數()
watchCallBack 當被檢測的對象發生變化時,執行該回調函數;改回調函數有三個參數
watchCallBack(newValue,oldValue,scope);java

  • newValue 被檢測對象watchObj的新的值
  • oldValue 被檢測對象watchObj的老的值
  • scope 當前控制器的$scope;
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
    <script type="text/javascript" src="main.js"></script>
</head>
<body>
    <div ng-controller="watchController">
        <input type="text" ng-model="yourInput">
        <div>{{result}}</div>
    </div>
</body>
</html>

main.jsjquery

var myappModule=angular.module('myApp',[]);

myappModule.controller('watchController',  function($scope){
    $scope.yourInput=1;
    $scope.watchCallBack=function(newValue,oldValue,scope){
        $scope.result=$scope.yourInput*4;
        console.log(newValue);
        console.log(oldValue);
    }
    $scope.$watch('yourInput',$scope.watchCallBack,false);
});

css 樣式

點擊高亮效果
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
    <script type="text/javascript" src="main.js"></script>
    <style type="text/css">
    .active{
    background-color: red;
    color:#fff;
    }
    </style>
</head>
<body>
    <div ng-controller="liController">
        <ul>
            <li ng-repeat="li in lis" ng-class="{active:$index==selted}" ng-click="choose($index)">
                {{li.title}}
            </li>
        </ul>
    </div>
</body>
</html>

點擊li 列表 通過 ng-click="choose($index)" ,將當前的$index 傳入到$scope.selted;
當ng-class="{active:$index==selted}" 為真,添加class active
main.js
---angularjs

var myappModule=angular.module('myApp',[]);
myappModule.controller('liController',function($scope){
    $scope.lis=[{"title":"text1"},{"title":"text2"},{"title":"text3"},{"title":"text4"}];
    $scope.choose=function(_index){
        $scope.selted=_index;
    }
})

module 服務

在不一樣的控制器中須要用到相同的數據時,就須要 用到服務;ajax

  • 先創建一個模塊;
  • 然後通過如下三種API來創建服務;
  • 使用時,注入到須要用到的模塊中;
var FactoryModule=angular.module('factoryData',[]);
FactoryModule.factory('factoryLists', function(){
    var lists={};
    lists.all=function(){
        return [{
            "title":"textli1"
        },{
            "title":"textli2"
        },{
            "title":"textli3"
        }]
    }
    return lists;
})

var myappModule=angular.module('myApp',['factoryData']);

myappModule.controller('factoryController',  function($scope,factoryLists){
$scope.lists=factoryLists.all();
});

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
    <script type="text/javascript" src="main.js"></script>
</head>
<body>
    <div ng-controller="factoryController">
         <ul>
            <li ng-repeat="li in lists">
                {{li.title}}
            </li>
         </ul>
    </div>
</body>
</html>

指令修改dom

  • 新建一個模塊
  • 然後再建一個指令;
var directiveModule=angular.module('directiveModule',[]);
directiveModule.directive('directiveName',  function(){
    // Runs during compile
    return {
        // name: '',
        // priority: 1,
        // terminal: true,
        // scope: {}, // {} = isolate, true = child, false/undefined = no change
        // controller: function($scope, $element, $attrs, $transclude) {},
        // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
        // restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
        // template: '',
        // templateUrl: '',
        // replace: true,
        // transclude: true,
        // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
        link: function($scope, iElm, iAttrs, controller) {
            
        }
    };
});

其中:express

  • directive 傳入二個參數
    1. 第一個參數為 指令的名稱;必須是駝峯命名 'testDirective' 若是是test-Directive 是錯誤的;在視圖中則使用test-directive
    2. 第二個參數為 一個工廠函數 返回一個json對象;
    3. 其中 該函數返回一個對象,對象的link 方法的函數有四個參數:
    • $scope 獲取外層scope的引用
    • iElm 它所在的DOM元素
    • attrs 傳遞給指令的一個屬性數組
    • controller DOM元素上的控制器
    1. templateUrl 的模板必需要有個父標籤 如div;
      ```
      var demo=angular.module('dectiveDemo',[]);
      demo.controller('dectiveCtrl', function(){

}).directive('demoDiv', function(){
// Runs during compile
return {
restrict: 'AECM', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'demo.html',
replace: true,
link: function($scope, iElm, iAttrs, controller) {npm

}
};

});
---html

json






--- #### 指令 transclude 默認的狀況下: transclude:false;//不使用transclude 這個屬性; transclude:true;//使用transclude 屬性的便籤; * 在指令視圖中 包含一些內容 這裏稱爲 一團數據 * 在指令的模板中用一個ng-transclude 這樣渲染視圖的時候,將上面的一團數據 放進這裏的ng-transclude 標籤中; 以下:java
var demo=angular.module('dectiveDemo',[]);
demo.controller('dectiveCtrl', function(){

}).directive('demoDiv', function(){
// Runs during compile
return {
restrict: 'AECM', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'demo.html',
replace: true,
transclude:true,
link: function($scope, iElm, iAttrs, controller) {

}
};

});
html



這裏是原來就存在的段落;若是transclude=true ,這裏的內容將被保留起來,若是translate=false,這裏的內容將不被保留




--- ### 指令 scope 指定該指令的控制域 * scope:false,//默認,控制域爲當前指令所在元素的自己; * scope:true,//指令能夠訪問到父做用域裏的值,父做用域的屬性值一旦被修改,子做用域裏相應的屬性值也會被修改,可是子做用域裏的屬性值修改,不會影響到父做用域裏的屬性值 * scope:{} @ //綁定能讓獨立做用域訪問到父做用域裏綁定的屬性值,可是獨立做用域下的這個值被修改,不影響到父做用域.相似於scope:true,可是僅僅是綁定的屬性,而不是所有的屬性. = //獨立做用域和父做用域之間的某個屬性徹底共享,不管是父做用域下這個屬性被修改仍是獨立做用域下這個屬性被修改,另外一個做用域下的這個屬性都會同步變化. & //獨立做用域能夠訪問父做用域裏的函數.html






注意: * 在demo-div 中父控制器中的parentCtrl 賦值給了 demo-div 的屬性attrs-demo ,而後有經過指令的scope 賦值到了childrenCtrl 。這樣模板中的childrenCtrl 就是綁定了 父控制器的parentCtrl 值; * 同時注意到,attrs-demo={{parentCtrl}} 這裏是 {{}} ;java
var demo=angular.module('dectiveDemo',[]);
demo.controller('dectiveCtrl', function($scope){
$scope.parentCtrl='parent';
}).directive('demoDiv', function(){
// Runs during compile
return {
restrict: 'AECM', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'demo.html',
replace: true,
transclude:true,
scope:{
childrenCtrl:'@attrsDemo'
},
link: function($scope, iElm, iAttrs, controller) {

}
};

});
注意:@attrsDemo 中attrsDemo使用了駝峯命名;指令的視圖中則爲 attrs-demo ---html






注意到: * attrs-demo=parentCtrl 是 =java
var demo=angular.module('dectiveDemo',[]);
demo.controller('dectiveCtrl', function($scope){
$scope.parentCtrl='parent';
}).directive('demoDiv', function(){
// Runs during compile
return {
restrict: 'AECM', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'demo.html',
replace: true,
transclude:true,
scope:{
childrenCtrl:'=attrsDemo'
},
link: function($scope, iElm, iAttrs, controller) {

}
};

});
```
注意:

  • childrenCtrl:'=attrsDemo' 也是使用了駝峯命名法;

指令 require 和controller (指令與父指令通訊,指令使用父指令中的controller)

<div parent-directive>
            <div child-directive></div>
        </div>
.directive('parentDirective',function(){
    return {
        restrict:'AECM',
        controller:function($scope){
            this.callByChild=function(childScope){
                console.log('這個函數能夠被子指令調用,還能夠調子指令的 link 裏面的數據  如:'+ childScope.data);
            }
        }
    }
}).directive('childDirective',  function(){
    // Runs during compile
    return {
         require: '^?parentDirective', // Array = multiple requires, ? = optional, ^ = check parent elements
         restrict: 'AECM', // E = Element, A = Attribute, C = Class, M = Comment
        link: function($scope, iElm, iAttrs, controller) {
            $scope.data='我是子指令的數據咯!!! ';
            controller.callByChild($scope); //調用父指令的controller 裏面的callByChild h函數;
        }
    };
});

注意:

  • childDirective 中的require 的^?parentDirective爲想外層查找指令 parentDirective ,^爲找到爲止,?爲若是沒有找到也不會報錯!!

指令 例子 datapicker

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
    <script type="text/javascript" src="angular.js"></script>

注意:引用的順序

  • jquery.js
  • jquery-ui.js
  • angularjs
<div id="wrapper" >
  <p>{{datePicker || "00/00/0000"}}</p>
  <input type="text" ng-model="datePicker" datepicker />
</div>
.directive("datepicker", function () {
  return {
    restrict: "AECM",
    require: "ngModel",
    link: function (scope, elem, attrs, ngModelCtrl) {
      var updateModel = function (dateText) {
        scope.$apply(function () {
          ngModelCtrl.$setViewValue(dateText);
        });
      };
      var options = {
        dateFormat: "dd-mm-yy",
        onSelect: function (dateText) {
          updateModel(dateText);
        }
      };
      elem.datepicker(options);
    }
  }
});

注意到:

  • require: "ngModel" 須要angular 的內置指令ngModel ,和寫法;
  • ngModelCtrl.$setViewValue(dateText); 這裏設置了指令的視圖中的 ng-model的值;
  • scope.$apply() 則是立刻渲染視圖;

$http.get

$http.get('url',{}).sucess(function(data,status,config){}).error(function(data,status,header,config){});

  • url: 請求的路徑
  • json對象: 請求的參數配置,如{params:{id:5}} 獲得的路徑為 url?id=5
  • sucess 請求成功的囘調
  • error 請求失敗的囘調
  • sucess 和 error 有四個參數 :
    • data 返回的數據
    • status 返回的響應的狀態碼
    • headers
    • congfig 請求的配置對象;
    {
       method:"GET",
       url:"/api/user"
       parmas:{id:5}
    
        }

    新建一個模塊 負責http 請求

    var httpGet=angular.module('httpGet',[]);
    httpGet.factory('httpGets', function($http,$q){
     return function (){
         var defer=$q.defer();
         $http.get('app.js').success(function(data,status,header){
             defer.resolve(data);
         }).error(function(data,status,header){
             defer.reject(data);
         });
         return defer.promise;
     };
    })

    注入以上的模塊'httpGet',同時注入依賴 'httpGets'
    ```java
    var myappModule=angular.module('myApp',[httpGet']);

myappModule.controller('factoryController', function($scope,httpGets){
$scope.getHttp=function(){
httpGets().then(function(data){
console.log(data);
}, function(data){
console.log(data);
})
}
});
--- ### $http.post $http.post('url',{},{}).success(function(data,status,header,config){}).error(function(data,status,header,config){}); * url 請求的路徑 * 請求發送的數據:json 對象 {name:'debbie'} * 請求配置的參數 :json 對象 {params:{id:5}} 獲得實際的路徑 url?id=5 * 其餘的跟get 一樣;java
var httpPOST=angular.module('httpPost',[]);
httpPOST.factory('getData',function($http,$q){
return function(){
var defer = $q.defer();
$http.post('http://localhost:3000/path/',jsonData,{headers:{'Content-Type':'application/x-www-form-urlencoded'}}).success(function(data,status,headers,congfig){
defer.resolve(data);
}).error(function(data,status,headers,congfig){
defer.reject(data);
});

return defer.promise
}

});
---java
$scope.postHttp=function(){
getData().then(function(data){console.log(data)}, function(data){console.log(data)});
};
```

不要忘記注入以上的模塊'httpPost',同時注入依賴 'getData'

過濾器 filter

filter

  • 過濾不符合條件的,
  • 或者格式化數據;
    內置的過濾器有許多,如今自定義本身的過濾器;
var myapp=angular.module("myapp",[]);
myapp.controller('filterCtrl', ['', function(){
    
}]).filter("filterName",function(){
    var filterString=function(_data,_condition){
        return _data+' -->debbie';
    }
    return filterString;
});

定義了一個 名爲 filterName 的過濾器, 返回一個 數據filterString,filterString就是由 須要過濾器過濾的數據加' -->debbie' 字符串而來;

<input ng-model="myyear">
    {{myyear | filterName}}

再來一個時間戳 轉爲時間格式的過濾器

var myapp=angular.module("myapp",[]);
myapp.controller('filterCtrl',function($scope){
$scope.time="1427858024";   
}).filter('timeFormat',function(){
    var timeString=function(_time,_condition){
        return new Date(parseInt( _time ) * 1000).toLocaleString().replace(/:d{1,2}$/,' ');
    };
    return timeString;
 });
<input ng-model="time">
    {{time | timeFormat}}

ngSanitize

ng-bind-html

  • 這個至關於jq裏面的 .text() .html()
  • 須要 angular-animate.min.js 在模塊中添加ngSanitize 依賴;
var myapp=angular.module("myapp",['ngSanitize']);
myapp.controller('filterCtrl',function($scope){
$scope.htmls='<a href="http://baidu.com/">baidu</a>';   
})
<p ng-bind-html="htmls"></p>

注意:$sanitize會把標籤的屬性都移除,以及綁定在元素上的事件.僅保留了標籤和內容,因此有時仍是須要用到下面的這個的

  • 仍是能夠用$sec 這個內置的服務;
var myapp=angular.module("myapp",['ngSanitize']);
myapp.controller('filterCtrl',function($scope,$sce){
$scope.htmls='<a href="http://baidu.com/" ng-click="test()">baidu</a>'; 
$scope.SCEhtml=$sce.trustAsHtml($scope.htmls);
})
<p ng-bind-html="SCEhtml"></p>

注意:$sce 保留了全部的屬性和事件;

linky 過濾器;

linky 根據ng-bind-html裏面的文本的內容(http https FTP mailto /email) 轉換成HTML的連接 即加個a 便籤 或者設置 a 便籤打開方式 (_blank,_self);

var myapp=angular.module("myapp",['ngSanitize']);
myapp.controller('filterCtrl',function($scope,$sce){
$scope.htmls='<a href="http://baidu.com/" ng-click="test()">baidu</a> http://google.com';   
})
<p ng-bind-html="htmls | linky"></p>
    <p ng-bind-html="htmls | linky :'_blank'"></p>

路由 $stateProvider /ui-router

  • 頁面加載'angular-ui-router.min.js 和一個 ui-view 屬性的便籤;
  • 模塊加入依賴 ui-router
<div ui-view></div>
var myapp=angular.module('myapp',['ui.router']);
myapp.config(function($stateProvider) {
    $stateProvider.state('demo1',{
        url:'/demo1',
        templateUrl:'demo.html'
    })
})

嵌入

var myapp=angular.module('myapp',['ui.router']);
myapp.config(function($stateProvider) {
    $stateProvider.state('parent1',{
        url:'/parent1',
        templateUrl:'parent.html'
    }).state('parent1.child',{
        url:'/child',
        templateUrl:'child.html'
    }).state('parent2',{
        url:'/parent2',
        templateUrl:'parent.html'
    })
})
<body ng-app="myapp" ng-controller="routerCtrl">
<a href="#/parent1">parent1</a>
<a href="#/parent2">parent2</a>
<a href="#/parent1/child">child</a>
<button ng-click="goto()">go parent1.child</button>
<div ui-view></div>
</body>
相關文章
相關標籤/搜索