angularjs笔记

1、
//只有provider和常量才能配置到config中
2、AngularJS模块可以在被加载和执行之前对模块自身进行配置。当你需要在AngularJS模块加载之前进行配置,就要用到config。只有提供者(Provider)和常量(constant)才能注入到config中。使用情形:
定义路由信息:
var app = angular.module('myApp', [ngRoute]);
app.config(["$routeProvider",function($routeProvider]){
//code
});
使用自定义的服务:
(注意:seivce定义的服务不能在config中使用!只有provider定义的才可以)
app.config(["$provide",function($provide]){
$provide.provider(){}
})
 
 

ngularJS提供例如许多内在的服务,如:$http, $route, $window, $location等。每个服务负责例如一个特定的任务,$http是用来创建AJAX调用,以获得服务器的数据。 $route用来定义路由信息等。内置的服务总是前缀$符号。

有两种方法来创建服务。

  • 工厂

  • 服务

使用工厂方法

使用工厂方法,我们先定义一个工厂,然后分配方法给它。

      var mainApp = angular.module("mainApp", []);
      mainApp.factory('MathService', function() {     
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b 
         }
         return factory;
      }); 

使用服务方法

使用服务的方法,我们定义了一个服务,然后分配方法。还注入已经可用的服务。

mainApp.service('CalcService', function(MathService){
    this.square = function(a) { 
		return MathService.multiply(a,a); 
	}
});

例子

下面的例子将展示上述所有指令。

testAngularJS.html
<html>
<head>
   <title>Angular JS Forms</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="CalcController">
      <p>Enter a number: <input type="number" ng-model="number" />
      <button ng-click="square()">X<sup>2</sup></button>
      <p>Result: {{result}}</p>
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script>
      var mainApp = angular.module("mainApp", []);
      mainApp.factory('MathService', function() {     
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b 
         }
         return factory;
      }); 

      mainApp.service('CalcService', function(MathService){
            this.square = function(a) { 
            return MathService.multiply(a,a); 
         }
      });

      mainApp.controller('CalcController', function($scope, CalcService) {
            $scope.square = function() {
            $scope.result = CalcService.square($scope.number);
         }
      });
   </script>
</body>
</html>

结果

在Web浏览器打开textAngularJS.html。看到结果如下。

AngularJS Services
 


猜你喜欢

转载自blog.csdn.net/qq_41987575/article/details/80395429