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)

宝剑锋从磨砺出,梅花香自苦寒来。
原文地址:https://www.cnblogs.com/haimengqingyuan/p/7395755.html