AngularJS學習筆記,angularjs
AngularJS學習筆記
最近在學習MEAN架構,其中前端的部分就是AngularJS,AngularJS和以前接觸的jQuery不同,它是通過給html添加directive(標記)的方式來增強html的互動能力的,我覺得它的雙端綁定做得很棒,並且能夠解耦邏輯和介面,的確是個值得學習的前端架構。
1、有關Controller
<div ng-controller="MyController">
{{person.name }}
</div>
app.controller('MyController',function($scope) {
$scope.person = {
name: "Ari Lerner"
};
});
這裡的person.name就對應著帶底紋的文字。
因為$scope就代表這個MyController中的任意子項目。
2、如何書寫services?
一般在網站的public檔案夾中,建立一個services,它的作用是可以在Controllers中共用資料。它是單例,只被執行個體化一次。
在services檔案夾中建立一個XXX.js,然後寫出這些代碼:
angular.module('myApp.services', [])
.factory('githubService', function() {
var serviceInstance = {};
// 我們的第一個服務
return serviceInstance;
});
這個僅僅是一個例子,它並沒有做任何事情。
可以將其擴充成為github的服務,下面黃色的部分就是新增的,可以看出,這裡依賴的$http作局部重新整理:
angular.module('myApp.services', [])
.factory('githubService', ['$http',function($http) {
var doRequest = function(username, path) {
return $http({
method: 'JSONP',
url: 'https://api.github.com/users/' +username + '/' + path + '?callback=JSON_CALLBACK'
});
}
return {
events: function(username) { returndoRequest(username, 'events'); },
};
}]);
如何在Controller中添加Services呢?
app.controller('ServiceController',['$scope', 'githubService',
function($scope, githubService) {
}]);
這種方法,在public/controllers中填寫,這樣將我們寫的githubService匯入進來了。
3、如何寫Routing
路由的作用是我們能夠順利地將後台模板整合到一個View中,達到模組化載入。
通過$routeProvider來實現。
<header>
<h1>Header</h1>
</header>
<div class="content">
<div ng-view></div>
</div>
<footer>
<h5>Footer</h5>
</footer>
ng-view指令將告訴$routeProvider在哪裡渲染模板。
下面主要設定$routeProvider的when函數以及otherwise函數。
when函數的第一個參數是設定路徑,可以為/或者是$location.path();
第二個參數是設定物件,這個對象有包含不同的鍵:
1)controller;這個controller可以指令碼中的某一個controller,也可以是現寫的函數,它的函數參數是function ( $scope ) { }
2)template;接受的是字串,模板會被渲染到DOM中的ng-view中。
例子:template:'<div><h2>Route</h2></div>'
3)templateUrl;和template差不多,只是設定了Url。
例子:
angular.module('myApp', []).
config(['$routeProvider',function($routeProvider) {
$routeProvider.when('/', {
controller: 'HomeController',
template: '<h2>We are home</h2>'
})
.otherwise({redirectTo: '/'});
}]);
如果指定了類似:的路由,那麼可以通過Controller來訪問到$routeParams。
$routeProvider.when('/person/:id', {
controller: 'PeopleController',
template: '<div>Person show page: {{ name }}</div>'
})
在PeopleController中,我們檢索路由中指定的people的:id
app.controller('PeopleController', function($scope,$routeParams) {
// We now have access to the $routeParams
// At the route /person/42, our$routeParams will look like:
// { id: 42 }
// 應該是
$routeParams.person.id = 42;
});
4、經驗談
實際使用的過程中,一個頁面以一個Controller為宜。並且Angular變數的初始化不建議在ng-init中完成,而是在controller中完成。
5、經驗教訓
在引用Controller和Service的時候,還需要注意的是
var myApp = angular.module('myApp', []);
代表的是定義myApp,也就是說通過名稱“myApp”和依賴[]來建立的一個Angular模組。而
var myApp = angular.module('myApp');
代表的是引用myApp這個模組,和上面的不同。如果嘗試兩個地方都調用了
var myApp = angular.module('myApp', []);
那麼在console就會報錯:
Error:$injector:unpr
Unknown Provider
我就曾經在這個地方困擾了很久。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。