AngularJS入門教程記錄

參考:http://docs.angularjs.org/tutorial/html

建立Moduleangularjs

使用module()方法。在第2個參數中傳入依賴模塊數組。json

var phonecatApp = angular.module('phonecatApp', [
    'ngRoute',
    'phonecatControllers'
]);

註冊Controller數組

使用controller()方法。ide

NG識別參數名並自動注入依賴。若使用代碼壓縮,則參數名將被壓縮從而沒法使用自動注入。函數

使用如下兩種顯式注入方式可解決代碼壓縮帶來的問題。url

方式1、spa

function PhoneListCtrl($scope, $http) {...}
PhoneListCtrl.$inject = ['$scope', '$http'];
phonecatApp.controller('PhoneListCtrl', PhoneListCtrl);

方式2、翻譯

function PhoneListCtrl($scope, $http) {...}
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', PhoneListCtrl]);

註冊控制器時一般採用匿名函數的寫法code

phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http) {...}]);

使用$http模塊進行HTTP請求

請求url爲'phones/phones.json',並經過success方法設置請求成功後的回調函數。

NG將自動偵測JSON響應並解析。

$http.get('phones/phones.json').success(function(data) {
    $scope.phones = data;
});

註冊Service

註冊服務,須要建立一個依賴於ngResource【angular-resource.js】的模塊。

使用factory方法(除此以外還有provide()和service()方法),顯式注入ngResource.$resource。

教程中沒有對$resource解釋得比較清楚,故而參考了在線文檔,並翻譯以下:

http://www.cnblogs.com/koukabatsugun/p/3442525.html

var phonecatServices = angular.module('phonecatServices', ['ngResource']);
 
phonecatServices.factory('Phone', ['$resource',
    function($resource){
        return $resource('phones/:phoneId.json', {}, {
            query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
}]);

以上,$resouce的第三個參數actions中,覆蓋了默認的query動做。

一、設置HTTP請求爲GET方法。

二、指定url模板中的【phoneId】參數爲【phones】。

三、返回值爲數組。

使用Phone服務的參考代碼以下:

$scope.phones = Phone.query();

$scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
    $scope.mainImageUrl = phone.images[0];
});

定義Router

爲應用配置路由,須要建立一個依賴於ngRoute【angular-route.js】的模塊。

使用模塊的config()方法,顯式注入ngRoute.$routeProvider。

var phonecatApp = angular.module('phonecatApp', [
    'ngRoute',
    'phonecatControllers'
]);
 
phonecatApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
          when('/phones', {
              templateUrl: 'partials/phone-list.html',
              controller: 'PhoneListCtrl'
          }).
       when('/phones/:phoneId', {
              templateUrl: 'partials/phone-detail.html',
              controller: 'PhoneDetailCtrl'
          }).
          otherwise({
              redirectTo: '/phones'
    });
}]);

從URL中獲取參數

依賴$routeParams。

從【/phones/:phoneId】中獲取phoneId,只需$routeParams.phoneId。

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams',
    function($scope, $routeParams) {
        $scope.phoneId = $routeParams.phoneId;
}]);
相關文章
相關標籤/搜索