angularjs-雜項

Sublime 代碼編輯工具
Webstorm 代碼編輯工具 file setring 設置插件
Chrome 瀏覽器 Batarang調試工具
Github gitTortoise圖形化界面
Grunt Js文件合并、代碼壓縮,Ctrl+s 自動執行,Ctrl+s集成測試
Nodejs
Karma 單元測試 Jasmime單元測試

一、$http 服務使用

var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http',
    function($http) {
        var doRequest = function(username, path) {
            return $http({
                method: 'GET',
                url: 'users.json'
            });
        }
        return {
            userList: function(username) {
                return doRequest(username, 'userList');
            }
        };
    }
]);
//自己定義的service放在最后
myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
    function($scope, $timeout, userListService) {
        var timeout;
        $scope.$watch('username', function(newUserName) {//監控前臺數據變化
            if (newUserName) {
                if (timeout) {
                    $timeout.cancel(timeout);
                }
                timeout = $timeout(function() {
                    userListService.userList(newUserName)
                        .success(function(data, status) {
                            $scope.users = data;
                        });
                }, 350);
            }
        });
    }
]);

二、Filter實現

myModule.filter('filter1',function(){
    return function(item){
        return item + 'o()o';
    }
});  
<body>   {{'大漠窮秋'|filter1 }}
</body>
第二章 代碼總結
var bookStoreApp = angular.module('bookStoreApp', [
    'ngRoute', 'ngAnimate', 'bookStoreCtrls', 'bookStoreFilters',
    'bookStoreServices', 'bookStoreDirectives'
]);

bookStoreApp.config(function($routeProvider) {
    $routeProvider.when('/hello', {
        templateUrl: 'tpls/hello.html',
        controller: 'HelloCtrl'
    }).when('/list', {
        templateUrl: 'tpls/bookList.html',
        controller: 'BookListCtrl'
    }).otherwise({
        redirectTo: '/hello'
    })
});

一、Directive示例
1.Link函數和scope

var app=angular.module("helloWordApp",[]);
app.controller('MainCtrl',function($scope){
    $scope.color="red";
});
app.directive("helloWord",function(){
    return {
        restrict:'AE',//A屬性E元素template替換,Cclass,默認A
        replace:true,//替換掉自己的標簽
     template:'<p style="background-color:{{color}}">hellorWord</p>',
    //link函數主要用來為DOM元素添加事件監聽、監視模型屬性變化、以及更新DOM
        link: function(scope,elem,attrs ){ //scope就是父controller的scope。
            elem.bind('click',function(){
               elem.css('background-color','white');
                scope.$apply(function(){
                    scope.color="white";
                });
            });
            elem.bind('mouseover',function(){
                elem.css('cursor','pointer');
            });
        }
    };
});
<div ng-controller="MainCtrl">
    <input type="text" ng-model="color"  placeholder="Enter aColor"/>
    <hello-word/>
</div>

2.Compile
compile 函數在 link 函數被執行之前用來做一些DOM改造。它接收下面的參數:
?tElement – 指令所在的元素
?attrs – 元素上賦予的參數的標準化列表
要注意的是 compile 函數不能訪問 scope,并且必須返回一個 link 函數。

app.directive('test', function() {
    return {
        compile: function(tElem,attrs) {
            //do optional DOM transformation here
            return function(scope,elem,attrs) {
                //linking function here
            };
        }
    };
});

3.其他兩種改變作用域的例子,默認false繼承不隔離,true繼承隔離{}隔離

app.directive('helloWorld', function() {
    return {
        scope: true,
// use a child scope that inherits from parent
        restrict: 'AE',
        replace: 'true',
        template: '<h3>Hello World!!</h3>'
    };
});
app.directive('helloWorld', function() {
    return {
        scope: {},  // use a new isolated scope,父作用域無法看到子作用域,完全隔離
        restrict: 'AE',
        replace: 'true',
        template: '<h3>Hello World!!</h3>'
    };
});

4.例子

var expanderModule=angular.module('expanderModule', [])
expanderModule.directive('expander', function() {
    return {
        restrict : 'EA',
        replace : true,
        transclude : true,
        scope : {
            title : '=expanderTitle'
        },
        template : '<div>'
        + '<div class="title" ng-click="toggle()">{{title}}</div>'
        + '<div class="body" ng-show="showMe" ng-transclude></div>'
        + '</div>',
        link : function(scope, element, attrs) {
            scope.showMe = false;
            scope.toggle = function toggle() {
                scope.showMe = !scope.showMe;
            }
        }
    }
});
expanderModule.controller('SomeController',function($scope) {
    $scope.title = '點擊展開';
    $scope.text = '這里是內部的內容。';
});

HTML代碼:

    <div ng-controller='SomeController'>
    <expander class='expander' expander-title='title'>
    {{text}}
</expander>
</div>

5.Transclude指定替換的位置ng-transclude

var app = angular.module("app", [])
    .directive("hello", function () {
        var option = {
            restrict: "AECM",
            template: "<h3>Hello, Directive, <span ng-transclude></span></h3>",
            replace: true,
            transclude: true
        };
        return option;
    })
<hello>12345678</hello>
//替換為了
<h3>Hello, Directive, <span ng-transclude=""><span class="ng-scope">12345678</span></span></h3>

6.Scope配合@,=,&數據綁定
(1)@單向綁定

var myApp=angular.module('myApp',[]);
myApp.controller('listCtrl',function($scope){
    $scope.logchore="motorola";
});
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            title:"@"
        },
        template:'<div >{{title}}</div>'

    }
});
<div ng-controller="listCtrl">
    <input type="text"  ng-model="t" />
    <kid title="{{t}}" >  //這個必須指定的,這里的title是指令里scope的@對應的,t就是控制域scope下的
    <span>我的angularjs</span>
    </kid>
    </div> 

(2)=雙向綁定

    <div ng-controller="listCtrl">
    <input type="text"  ng-model="t" />
    <kid title="t" > //和上面相比,這個直接賦值等于scope域下的t了
       <p>{{title}}</p>
       <span>我的angularjs</span>
       </kid>
    </div>
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            title:"="
        },
        template:'<div >{{title}}</div>'

    }
});

(3)最后說&,這個是用來方法調用的

 <kid flavor="logchore(t)" ></kid>   
myApp.directive('kid',function(){
    return {
        'restrict':'E',
        scope:{
            flavor:"&"
        },
        template:'<div >    <input type="text"  ng-model="v" /> <button ng-click="flavor({t:v})"></button></div>'
    }
});
myApp.controller('listCtrl',function($scope){
    $scope.logchore=function(x){
        alert(x);
    };
});

7、Controller

//controller
appControllers.controller('mainCtrl', ['$scope',
  function($scope) {
    $scope.changedTime = function(time) {
      alert(time);
    }
  }]).directive('timePicker',['$http', function($http) {
  return {
    restrict: 'AE',
    templateUrl: 'partials/time-picker.html',
    scope: true,
    controller: 'TimepickerDemoCtrl'
  };
}]);


//partials/time-picker.html:
<span ng-controller="TimepickerDemoCtrl">
    <timepicker ng-model="mytime" ng-change="changed()" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></timepicker>
    </span>
//TimepickerDemoCtrl (copy from source):
var TimepickerDemoCtrl = function ($scope) {
  $scope.mytime = new Date();
  $scope.hstep = 1;
  $scope.mstep = 15;
  $scope.options = {
    hstep: [1, 2, 3],
    mstep: [1, 5, 10, 15, 25, 30]
  };
  $scope.ismeridian = true;
  $scope.toggleMode = function() {
    $scope.ismeridian = ! $scope.ismeridian;
  };
  $scope.update = function() {
    var d = new Date();
    d.setHours( 14 );
    d.setMinutes( 0 );
    $scope.mytime = d;
  };
  $scope.changed = function () {
    console.log('Time changed to: ' + $scope.mytime);
  };
}

8.一個重要的tab例子,涉及到controller作用域等

<body ng-app="components">
<h3>BootStrap Tab Component</h3>
<tabs>
    <pane title="First Tab">
        <div>This is the content of the first tab.</div>
    </pane>
    <pane title="Second Tab">
        <div>This is the content of the second tab.</div>
    </pane>
</tabs>
</body>
angular.module('components', []).
    directive('tabs', function() {
        return {
            restrict: 'E',
            transclude: true,
            scope: {},
            controller: [ "$scope", function($scope) {
                var panes = $scope.panes = [];
                $scope.select = function(pane) {
                    angular.forEach(panes, function(pane) {
                        pane.selected = false;
                    });
                    pane.selected = true;
                }
                this.addPane = function(pane) {
                    if (panes.length == 0) $scope.select(pane);
                    panes.push(pane);
                }
            }],
            template:
            '<div class="tabbable">' +
            '<ul class="nav nav-tabs">' +
            '<li ng-repeat="pane in panes" ng-class="{active:pane.selected}">'+
            '<a href="" ng-click="select(pane)">{{pane.title}}</a>' +
            '</li></ul>' +
            '<div class="tab-content" ng-transclude></div></div>',
            replace: true
        };
    }).
    directive('pane', function() {
        return {
            require: '^tabs',//^在指令的上游查找控制器,?當前指令,沒有前綴,自身所提供的控制器中查找;本例是吧tabs中的控制器傳入
            restrict: 'E',
            transclude: true,
            scope: { title: '@' },
            link: function(scope, element, attrs, tabsCtrl) {
                tabsCtrl.addPane(scope);
            },
            template:
            '<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>',
            replace: true
        };
    })

二、Service示例
1.服務器請求http

angular.module('myApp.services', [])
    .factory('githubService', ['$http', function($http) {
      var githubUsername;
      var doRequest = function(path) {
        return $http({
          method: 'JSONP',
          url: 'https://api.github.com/users/' + githubUsername + '/' + path + '?callback=JSON_CALLBACK'
        });
      }
      return {
        events: function() { return doRequest('events'); },
        setUsername: function(newUsername) { githubUsername = newUsername; }
      };
    }]); 

2.一個音樂播放器服務

app.factory('player', ['audio', function(audio) {
  var player = {
    playing: false,
    current: null,
    ready: false,
    play: function(program) {
      // If we are playing, stop the current playback 
      if (player.playing) player.stop();
      var url = program.audio[0].format.mp4.$text; // from the npr API 
      player.current = program; // Store the current program 
      audio.src = url;
      audio.play(); // Start playback of the url 
      player.playing = true
    },
    stop: function() {
      if (player.playing) {
        audio.pause(); // stop playback 
        // Clear the state of the player 
        playerplayer.ready = player.playing = false;
        player.current = null;
      }
    }
  };
  audio.addEventListener('ended', function() {
    $rootScope.$apply(player.stop());
  }); 
  return player;
}]); 

二、Filter代碼示例
3.簡單示例

{{'大漠窮秋'|filter1 }}
myModule.filter('filter1',function(){
    return function(item){
        return item + 'o(∩_∩)o';
    }
});  

三、Http請求示例
1.后臺請求數據

myModule.controller('LoadDataCtrl', ['$scope','$http', function($scope,$http){
   $http({
        method: 'GET',
        url: 'data.json'
    }).success(function(data, status, headers, config) {
        console.log("success...");
        console.log(data);
        $scope.users=data;
    }).error(function(data, status, headers, config) {
        console.log("error...");
    });
}]);
//前端
<div ng-controller="LoadDataCtrl">
   <ul>
      <li ng-repeat="user in users">
         {{user.name}}
      </li>
   </ul>
</div>

2.Service+后臺請求數據

var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http',
    function($http) {
        var doRequest = function(username, path) {
            return $http({
                method: 'GET',
                url: 'users.json'
            });
        }
        return {
            userList: function(username) {
                return doRequest(username, 'userList');
            }
        };
    }
]);

myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
    function($scope, $timeout, userListService) {
        var timeout;
        $scope.$watch('username', function(newUserName) {
            if (newUserName) {
                if (timeout) {
                    $timeout.cancel(timeout);
                }
                timeout = $timeout(function() {
                    userListService.userList(newUserName)
                        .success(function(data, status) {
                            $scope.users = data;
                        });
                }, 350);
            }
        });
    }
]);
//前端
<div ng-controller="ServiceController">
  <label>用戶名</label>
  <input type="text" ng-model="username" placeholder="請輸入用戶名" />
  <pre ng-show="username">{{users}}</pre>
</div>

四、頁面跳轉傳參

$routeProvider.when('/gerenxiangqing/:userId', {templateUrl: 'xiangqing/gerenxiangqing.html',controller:'GeRenXiangQing', reloadOnSearch: false});
ziYuan.controller('GeRenXiangQing',function($scope,httpService,$routeParams){
    $scope.guanzhuInfo="關注";//button 顯示的信息
    $scope.id=$routeParams.userId;
    //判斷是否關注,然后顯示button信息
    httpService.events({id: $scope.id}, "userController/isGuanZhu")
               .success(function (data, status, headers, config) {
        if (data == 1) {//已關注
            $scope.guanzhuInfo = "已關注";
        } else if (data == 0) {//未關注
            $scope.guanzhuInfo = "關注";
        }
    }).error(function (data, status, headers, config) {
    });
 });

五、知識點
1.ng-repeat="message in messages track by $index"
$index $first $last
ng-class=”{‘selected’:true}”
2.ng-bing 等價于 {{}}
3.{{reverse()}} 方法可以直接調用
4.翻轉字符串 msg.split(“”).reverse().jion(“”);
5.服務 value 可以改變,constant不可以變,factory比較常用,service
6..factory('githubService', ['$http', function($http) {
return {
msg:”fd”;
alertInfo:function(){alert(“fd”)}
}
};
}]);

service('githubService', ['$http', function($http) {
              return {
              msg:”fd”;
          alertInfo:function(){alert(“fd”)}
           }
      };
 }]); 
factory('githubService', ['$http', function($http) {
            return new dd();              
     };
 }]); 
//等價于
Function dd(){
    this.mgs=”fd”;
    this.alertInfo=function(){alert(“fd”)}
}

8.多個service共享數據,Data是個共享的容器,比如購物車的使用

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,701評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,691評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,974評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,694評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,026評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,193評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,719評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,442評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,668評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,846評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,255評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,592評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,394評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,836評論 18 139
  • AngularJS是什么?AngularJs(后面就簡稱ng了)是一個用于設計動態web應用的結構框架。首先,它是...
    200813閱讀 1,631評論 0 3
  • AngularJS AngularJS概述 介紹 簡稱:ng Angular是一個MVC框架 其他前端框架: Vu...
    我愛開發閱讀 2,347評論 0 8
  • 指令定義 對于指令,可以把它簡單的理解成在特定DOM元素上運行的函數,指令可以擴展這個元素的功能。??我們可以自己...
    oWSQo閱讀 1,203評論 0 0
  • AngularJSAngularJS 是一個 MV* 框架, 最適于開發客戶端的單頁面應用。它不是個功能庫,...
    一直以來都很好閱讀 909評論 0 0