angularjs學習筆記--ng-model、controller、DI、$scope、$provide


依賴:

RESTful功能由angularjs在ngResource模塊中提供,該模塊與核心angularjs框架分開分發。

 

ng-model:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../angular/angular.js"></script>
</head>
<body>
   <div ng-app ng-init="qty=1;cost=2">
       <b>Invoice:</b>
       <div>
           Quantity:
           <input type="number" min="0" ng-model="qty" />
       </div>
       <div>
           Costs:
           <input type="number" min="0" ng-model="cost">
       </div>
       <div>
           <b>Total:</b>{{qty*cost|currency}}
       </div>
   </div>
</body>
</html>

 

Ps:required屬性規定必須在提交之前填寫輸入字段。

 

controllerindex.html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
    <script src="../angular/angular.js"></script> 
    <script src="../scripts/invoice1.js"></script> 
</head> 
<body> 
  <div ng-app="invoice1" ng-controller="InvoiceController as invoice"> 
     <b>Invoice:</b> 
      <div> 
          Quantity: 
          <input type="number" min="0" ng-model="invoice.qty" required> 
      </div> 
      <div> 
          Costs: 
          <input type="number" min="0" ng-model="invoice.cost" required> 
          <select ng-model="invoice.inCurr"> 
              <option ng-repeat="c in invoice.currencies">{{c}}</option> 
          </select> 
      </div> 
      <div> 
          <b>Total:</b> 
          <span ng-repeat="c in invoice.currencies">{{invoice.total(c)|currency:c}}</span><br> 
      </div> 
      <button class="btn" ng-click="invoice.pay()">Pay</button> 
  </div> 
</body> 
</html>

 

invoice1.js:

angular.module('invoice1',[]). 
    controller('InvoiceController',function InvoiceController(){ 
        this.qty = 1; 
        this.cost = 2; 
        this.inCurr = 'EUR'; 
        this.currencies = ['USD','EUR','CNY']; 
        this.usdToForeignRates = { 
            USD:1, 
            EUR:0.74, 
            CNY:6.09 
        }; 
        this.total = function total(outCurr){ 
            return this.convertCurrency(this.qty * this.cost,this.inCurr,outCurr); 
        }; 
        this.convertCurrency = function convertCurrency(amount,inCurr,outCurr){ 
            return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr]; 
        }; 
        this.pay = function pay(){ 
            window.alert("thanks"); 
        }; 
});

 

 

ps:控制器是JavaScript對象,由JavaScript對象的構造函數創建。控制器指向一個構造函數,該函數用於創建實際的控制器實例。控制器的目的是將變量和功能暴露給表達式和指令。

 

Ps:控制器的$scope用來保存angularjs model的對象。

 

 

controller2.html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
    <script src="../angular/angular.js"></script> 
    <script src="../scripts/finance2.js"></script> 
    <script src="../scripts/invoice2.js"></script> 
</head> 
<body> 
<div ng-app="invoice2" ng-controller="InvoiceController as invoice">   //這里綁定控制器名字部分不明白?? 
    <b>Invoice:</b> 
    <div> 
        Quantity: 
        <input type="number" min="0" ng-model="invoice.qty" required> 
    </div> 
    <div> 
        Costs: 
        <input type="number" min="0" ng-model="invoice.cost" required> 
        <select ng-model="invoice.inCurr"> 
            <option ng-repeat="c in invoice.currencies">{{c}}</option> 
        </select> 
    </div> 
    <div> 
        <b>Total:</b> 
        <span ng-repeat="c in invoice.currencies">{{invoice.total(c)|currency:c}} </span><br> 
    </div> 
    <button class="btn" ng-click="invoice.pay()">Pay</button> 
</div> 
</body> 
</html>

 

 

finance2.js:

angular.module('finance2',[]) 
.factory('currencyConverter',function(){ 
    var currencies = ['USD','EUR','CNY']; 
    var usdToForeignRates = { 
        USD:1, 
        EUR:0.74, 
        CNY:6.09 
    }; 
    var convert = function(amount, inCurr, outCurr){ 
        return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr]; 
    }; 
    return { 
        currencies:currencies, 
        convert:convert 
    }; 
});

 

invoice2.js:

angular.module('invoice2',['finance2']) 
.controller('InvoiceController',['currencyConverter',function InvoiceController(currencyConverter){
//將服務實例作為參數調用控制器 
    this.qty = 1; 
    this.cost = 2; 
    this.inCurr = 'EUR', 
    this.currencies = currencyConverter.currencies; 
    this.total = function total(outCurr){ 
        return currencyConverter.convert(this.qty *this.cost,this.inCurr,outCurr); 
    }; 
    this.pay = function pay(){ 
        window.alert('thanks'); 
    }; 
}]);

 

 

controllerindex.html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
    <script src="../angular/angular.js"></script> 
    <script src="../scripts/finance3.js"></script> 
    <script src="../scripts/invoice3.js"></script> 
 
</head> 
<body> 
<div ng-app="invoice3" ng-controller="InvoiceController as invoice"> 
    <b>Invoice:</b> 
    <div> 
        Quantity: 
        <input type="number" min="0" ng-model="invoice.qty" required> 
    </div> 
    <div> 
        Costs: 
        <input type="number" min="0" ng-model="invoice.cost" required> 
        <select ng-model="invoice.inCurr"> 
            <option ng-repeat="c in invoice.currencies">{{c}}</option> 
        </select> 
    </div> 
    <div> 
        <b>Total:</b> 
        <span ng-repeat="c in invoice.currencies">{{invoice.total(c)|currency:c}} </span><br> 
    </div> 
    <button class="btn" ng-click="invoice.pay()">Pay</button> 
</div> 
</body> 
</html>

 

finance3.js:

angular.module('finance3',[]) 
.factory('currencyConverter',['$http',function($http){ 
    var currencies = ['USD','EUR','CNY']; 
    var usdToForeignRates = {}; 
    var convert = function(amount, inCurr, outCurr){ 
        return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr]; 
    }; 
    var refresh = function(){ 
        var url = 'http://api.ficer.io/latest?base=USD&symbols=' + currencies.join(","); 
        return $http.get(url).then(function(response){ 
            usdToForeignRates = response.data.rates; 
            usdToForeignRates['USD'] = 1; 
        }); 
    }; 
    refresh(); 
    return { 
        currencies:currencies, 
        convert:convert 
    }; 
}]);

 

invoice3.js:

angular.module('invoice3',['finance3']) 
.controller('InvoiceController',['currencyConverter',function InvoiceController(currencyConverter){ 
    this.qty = 1; 
    this.cost =2; 
    this.inCurr = 'EUR'; 
    this.currencies = currencyConverter.currencies; 
    this.total = function total(outCurr){ 
        return currencyConverter.convert(this.qty * this.cost,this.inCurr,outCurr); 
    }; 
    this.pay = function pay(){ 
        window.alert("thanks"); 
    }; 
}]);

 

 

ps:

依賴注入(DI),一種軟件設計模式,用於處理如何創建對象和函數,以及如何保持其依賴性。Angularjs(指令、過濾器、控制器、服務等)內的所有內容都使用依賴注入進行創建和布線。在angularjs中,DI容器稱為注射器。要使用DI,需要有一個地方,所有的東西都可以在這里注冊,這就是angularjs中的模塊的作用。當angularjs啟動時,將通過ng-app指令使用模塊定義的名字的配置,包括該模塊所依賴的所有其他模塊的配置。

 

控制器:angularjs中,控制器由JavaScript構造函數定義,用於增加angularjs scope。當控制器通過ng-controller指令附加到DOM時,angularjs將使用指定的controller的構造函數進行實例化一個新的controller對象。將創建一個新的子范圍,並作為注入參數提供給controller的構造函數作為scope。

使用控制器:設置$scope對象的初始狀態(通過將屬性附加到$scope對象來設置作用域的初始狀態,屬性包含視圖模型);向$scope對象添加行為。

 

 

設置$scope對象的初始狀態:

controllerindex.html:

<!DOCTYPE html> 
<html lang="en" ng-app="myApp"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
    <script src="../angular/angular.js"></script> 
    <script src="../scripts/controller4.js"></script> 
</head> 
<body ng-controller="GreetingController"> 
   {{greeting}} 
</body> 
</html>

 

controller4.js:

var myApp = angular.module('myApp',[]); 
myApp.controller('GreetingController',['$scope',function($scope){ 
    $scope.greeting = 'Hola'; 
}]);

 

將行為添加到作用域對象上:

controllerindex5.html:

<!DOCTYPE html> 
<html lang="en" ng-app="myApp"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
    <script src="../angular/angular.js"></script> 
    <script src="../scripts/controller5.js"></script> 
</head> 
<body ng-controller="DoubleController"> 
  Two times <input ng-model="num" /> equals {{double(num)}} 
</body> 
</html>

 

controller5.js:

var myApp = angular.module('myApp',[]); 
myApp.controller('DoubleController',['$scope',function($scope){ 
    $scope.double = function(value){ 
        return value * 2; 
    }; 
}]);

 

ps:分配給作用域的任何對象都將成為模型屬性。

Ps:一般,控制器只包含單個視圖所需的所有業務邏輯。控制器的常見用法:將不屬於控制器的工作封裝到服務中,然后通過依賴注入在控制器中使用這些服務。

 

ng-controller指令用於為模板創建作用域,且該作用域通過對應controller進行擴充。

 

應用程序開發人員通過注冊服務名字與服務工廠函數可以定義自己的服務。服務工廠函數生成單一的對象或函數,服務通過模塊API注冊到模塊,通常使用模塊工廠API注冊服務:

var myModule = angular.module('myModule',[]); 
myModule.factory('serviceId',function(){ 
    var shinyNewServiceInstance; 
    //... 
    return shinyNewServiceInstance; 
});

 

 

服務可以有自己的依賴,就像在控制器中聲明依賴關系一樣,通過在服務的工廠函數簽名中指定它們來聲明依賴關系。

var batchModule = angular.module('batchModule', []); 
batchModule.factory('batchLog', ['$interval', '$log', function($interval, $log) { 
 
}

 

$provide注冊服務:可以通過模塊內的$provide服務的config函數注冊服務

angular.module('myModule',[]).config(['$provide',function($provide){ 
    $provide.factory('serviceId',function(){ 
        var shinyNewServiceInstance; 
        //... 
        return shinyNewServiceInstance; 
    }); 
}]);

 

可以在定義組件或為模塊提供run和config時,使用依賴注入。(1)服務、指令、過濾器、動畫的組件由可注入的工廠方法或構造函數定義,這些組件可以注入服務和值作為依賴關系。(2)控制器由構造函數定義,可以將任何服務和值組件作為依賴關系注入,但可提供特殊的依賴關系。(3)run方法接受一個可注入service、value、constant組件作為依賴關系的函數。(4)config方法接受一個函數,可以用provider和constant組件作為依賴關系注入。

 

$inject屬性是要注入一系列服務名稱

 

ng-model指令通過將模型與視圖同步以及查看模型來提供雙向數據綁定。

 

參考 & 感謝:https://docs.angularjs.org

(8-18)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM