Sublime 代碼編輯工具
Webstorm 代碼編輯工具 file setring 設(shè)置插件
Chrome 瀏覽器 Batarang調(diào)試工具
Github gitTortoise圖形化界面
Grunt Js文件合并智什、代碼壓縮,Ctrl+s 自動(dòng)執(zhí)行,Ctrl+s集成測(cè)試
Nodejs
Karma 單元測(cè)試 Jasmime單元測(cè)試
一、$http 服務(wù)使用
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) {//監(jiān)控前臺(tái)數(shù)據(jù)變化
if (newUserName) {
if (timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(function() {
userListService.userList(newUserName)
.success(function(data, status) {
$scope.users = data;
});
}, 350);
}
});
}
]);
二、Filter實(shí)現(xiàn)
myModule.filter('filter1',function(){
return function(item){
return item + 'o()o';
}
});
<body> {{'大漠窮秋'|filter1 }}
</body>
第二章 代碼總結(jié)
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函數(shù)和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煌张,默認(rèn)A
replace:true,//替換掉自己的標(biāo)簽
template:'<p style="background-color:{{color}}">hellorWord</p>',
//link函數(shù)主要用來為DOM元素添加事件監(jiān)聽苛白、監(jiān)視模型屬性變化娃豹、以及更新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 函數(shù)在 link 函數(shù)被執(zhí)行之前用來做一些DOM改造购裙。它接收下面的參數(shù):
?tElement – 指令所在的元素
?attrs – 元素上賦予的參數(shù)的標(biāo)準(zhǔn)化列表
要注意的是 compile 函數(shù)不能訪問 scope懂版,并且必須返回一個(gè) link 函數(shù)。
app.directive('test', function() {
return {
compile: function(tElem,attrs) {
//do optional DOM transformation here
return function(scope,elem,attrs) {
//linking function here
};
}
};
});
3.其他兩種改變作用域的例子,默認(rèn)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 = '點(diǎn)擊展開';
$scope.text = '這里是內(nèi)部的內(nèi)容薇芝。';
});
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配合@私股,=,&數(shù)據(jù)綁定
(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}}" > //這個(gè)必須指定的恩掷,這里的title是指令里scope的@對(duì)應(yīng)的倡鲸,t就是控制域scope下的
<span>我的angularjs</span>
</kid>
</div>
(2)=雙向綁定
<div ng-controller="listCtrl">
<input type="text" ng-model="t" />
<kid title="t" > //和上面相比,這個(gè)直接賦值等于scope域下的t了
<p>{{title}}</p>
<span>我的angularjs</span>
</kid>
</div>
myApp.directive('kid',function(){
return {
'restrict':'E',
scope:{
title:"="
},
template:'<div >{{title}}</div>'
}
});
(3)最后說&黄娘,這個(gè)是用來方法調(diào)用的
<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.一個(gè)重要的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',//^在指令的上游查找控制器逼争,优床?當(dāng)前指令,沒有前綴誓焦,自身所提供的控制器中查找胆敞;本例是吧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.服務(wù)器請(qǐng)求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.一個(gè)音樂播放器服務(wù)
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.簡(jiǎn)單示例
{{'大漠窮秋'|filter1 }}
myModule.filter('filter1',function(){
return function(item){
return item + 'o(∩_∩)o';
}
});
三移层、Http請(qǐng)求示例
1.后臺(tái)請(qǐng)求數(shù)據(jù)
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+后臺(tái)請(qǐng)求數(shù)據(jù)
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="請(qǐng)輸入用戶名" />
<pre ng-show="username">{{users}}</pre>
</div>
四、頁面跳轉(zhuǎn)傳參
$routeProvider.when('/gerenxiangqing/:userId', {templateUrl: 'xiangqing/gerenxiangqing.html',controller:'GeRenXiangQing', reloadOnSearch: false});
ziYuan.controller('GeRenXiangQing',function($scope,httpService,$routeParams){
$scope.guanzhuInfo="關(guān)注";//button 顯示的信息
$scope.id=$routeParams.userId;
//判斷是否關(guān)注赫粥,然后顯示button信息
httpService.events({id: $scope.id}, "userController/isGuanZhu")
.success(function (data, status, headers, config) {
if (data == 1) {//已關(guān)注
$scope.guanzhuInfo = "已關(guān)注";
} else if (data == 0) {//未關(guān)注
$scope.guanzhuInfo = "關(guān)注";
}
}).error(function (data, status, headers, config) {
});
});
五观话、知識(shí)點(diǎn)
1.ng-repeat="message in messages track by $index"
$index $first $last
ng-class=”{‘selected’:true}”
2.ng-bing 等價(jià)于 {{}}
3.{{reverse()}} 方法可以直接調(diào)用
4.翻轉(zhuǎn)字符串 msg.split(“”).reverse().jion(“”);
5.服務(wù) 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();
};
}]);
//等價(jià)于
Function dd(){
this.mgs=”fd”;
this.alertInfo=function(){alert(“fd”)}
}
8.多個(gè)service共享數(shù)據(jù),Data是個(gè)共享的容器秦叛,比如購(gòu)物車的使用