Angularjs API整理(一) function篇

 根据 http://docs.ngnice.com/api/ng网址下的  英文API文档进行学习归纳和总结。

  function篇,就理解成是在  js 文件中  或者 <script></script> 中才会被使用的 angular。

1.  angular.bind (格式:angular.bind(self(对象),fu(函数名),args(参数));

var app = angular.module('myApp', []);
app.controller("ShopController", function() {
    var goods={
        price:"88",
        name:"苹果6",
    };
    var fn=function(arg){
        console.log(this.name+"的价钱是:"+this.price+arg)
    };
    var one=angular.bind(goods,fn,"太好了"); //标注一
    one("22222");
    var two=angular.bind(goods,fn);//标注二
    two("22222");
  

})

如上面的例子 angulars.bind 就是把 goods 这个对象 绑定到 fn这个方法里面去,对应了fn方法里面的 this.

传参的方式有两种,如标注1,和标注二。 如果2个地方都传参,优先绑定 标注一的参数。

说一个细节,注意到使用var声明的变量吧,angular 不是都是在$scope声明的吗

简要说明一下 var和$scope的区别

如果上面的例子用$scope来实现,则代码如下

app.controller("ShopController2", function($scope) {
    $scope.goods={
        price:"88",
        name:"苹果6",
    };
    $scope.fn=function(arg){
        console.log(this.name+"的价钱是:"+this.price+arg)
    };
    $scope.one=angular.bind($scope.goods,$scope.fn);
    $scope.one("在$scope声明");
   

})

scopeAngularJScontrollerdirective文。

var部,只能在当前函数里使用。

最主要区别是$scope 会被$watch监听变化,而var你懂得。



2.  angular.bootstrap(模块的自动加载)

  语句:angular.bootstrap(element,[modules],[config]);

 element:  是绑定ng-app的dom元素;
modules:绑定的模块名字  config:附加的配置

**ng-app指令,可以实现模块的自动加载。


如:<body ng-app="myApp"ng-controller="ShopController">

在html标签里 使用 声明 即可 自动加载 "myApp" 模块

**angular.bootstrp,是手动加载模块。如



<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
<body id="body">
    <div ng-controller="myCtrl">  //  *1
        {{ hello }}
    </div>
    <script type="text/javascript">
        var app = angular.module("bootstrapTest",[]);
        app.controller("myCtrl",function($scope){
            $scope.hello = "hello,angular from bootstrap";
        });
        
       angular.bootstrap(document.getElementById("body"),['bootstrapTest']);
   
    </script>
</body>
</html>

如 *1 处没有使用 ng-app 加载指定模块。而是在script 里 使用angular.bootstrp 手动加载模块(

1.根据ID获取要注入的模块的 作用范围。

2.绑定要注入的模块名字,进而注入)      而后完成了 和< ng-app> 一样的功能。



3.  angular.copy

   angular.copy就是复制一个对象或者数组,即数据的拷贝,也就是内存中多了另外一份值相同,但是地址不同的数据。

相当于 鸣人的分身术,分为一号和二号分身,一个是小樱的,一个是雏田的。一样是鸣人,但是有2个。分别属于谁谁谁。

这里说一说,   $scope.user = angular.copy($scope.master);
               和$scope.user=$scope.master的区别。
第二种复制。相当于只有一个鸣人,即属于雏田也属于小樱。
说到底就是指向问题。意会  看例子
<!DOCTYPE html>  
<html ng-app="copyApp">  
<head>  
    <meta charset="UTF-8">  
    <title></title>  
    <script src="app/angular.js"></script>  
    <script>  
      var copyApp = angular.module("copyApp", [])  
              .controller("copyController", function($scope)  
              {  
                  $scope.dup = {};  
                  $scope.user =  
                  {  
                      name:"",  
                      password:"",  
                      friends:["zhangSan", "liSi"]  
                  }  
  
                  $scope.save = function(aUser)  
                  {  
                     $scope.dup =angular.copy(aUser);  
                  }  
  
                  $scope.modify = function(aUser)  
                  {  
                      aUser.name += "_newly";  
                      aUser.friends.push("wangWu");  
                  }  
              });  
    </script>  
</head>  
<body>  
  
<div ng-controller="copyController">  
    <form>  
        username:<input type="text" ng-model="user.name"/>  
        password:<input type="text" ng-model="user.password"/>  
    </form>  
    <button ng-click="save(user)">保存</button>  
    <button ng-click="modify(user)">修改</button>  
  
    <hr/>  
  
    原值:<pre>{{user}}</pre>  
    副本:<pre>{{dup}}</pre>  
  
</div>  
</body>  
</html>  

上述代码,user的值改变,dup不变,
绿色部分换成    $scope.dup=aUser
  则 user改变dup跟着改变。因为他们地址指向同一个数据。


4.  angular.element

       格式angular.element(element);

              element:包装成jquery对象的html字符串或者dom元素

DOM 元素或者 HTML 字符串一包装成一个 jQuery 元素。从而调用 jqLite 提供的方法 如下

addClass()-为每个匹配的元素添加指定的样式类名
after()-在匹配元素集合中的每个元素后面插入参数所指定的内容,作为其兄弟节点

append()-在每个匹配元素里面的末尾处插入参数内容

attr() - 获取匹配的元素集合中的第一个元素的属性的值

bind() - 为一个元素绑定一个事件处理程序

children() - 获得匹配元素集合中每个元素的子元素,选择器选择性筛选

clone()-创建一个匹配的元素集合的深度拷贝副本

contents()-获得匹配元素集合中每个元素的子元素,包括文字和注释节点

css() - 获取匹配元素集合中的第一个元素的样式属性的值

data()-在匹配元素上存储任意相关数据

detach()-DOM中去掉所有匹配的元素

empty()-DOM中移除集合中匹配元素的所有子节点

eq()-减少匹配元素的集合为指定的索引的哪一个元素

find() - 通过一个选择器,jQuery对象,或元素过滤,得到当前匹配的元素集合中每个元素的后代

hasClass()-确定任何一个匹配元素是否有被分配给定的(样式)类

html()-获取集合中第一个匹配元素的HTML内容

next() - 取得匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。如果提供一个选择器,那么只有紧跟着的兄弟元素满足选择器时,才会返回此元素

on() - 在选定的元素上绑定一个或多个事件处理函数

off() - 移除一个事件处理函数

one() - 为元素的事件添加处理函数。处理函数在每个元素上每种事件类型最多执行一次

parent() - 取得匹配元素集合中,每个元素的父元素,可以提供一个可选的选择器

prepend()-将参数内容插入到每个匹配元素的前面(元素内部)

prop()-获取匹配的元素集中第一个元素的属性(property)值

ready()-DOM准备就绪时,指定一个函数来执行

remove()-将匹配元素集合从DOM中删除。(同时移除元素上的事件及 jQuery 数据。)

removeAttr()-为匹配的元素集合中的每个元素中移除一个属性(attribute

removeClass()-移除集合中每个匹配元素上一个,多个或全部样式

removeData()-在元素上移除绑定的数据

replaceWith()-用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合

text()-得到匹配元素集合中每个元素的合并文本,包括他们的后代

toggleClass()-在匹配的元素集合中的每个元素上添加或删除一个或多个样式类,取决于这个样式类是否存在或值切换属性。即:如果存在(不存在)就删除(添加)一个类

triggerHandler() -为一个事件执行附加到元素的所有处理程序

unbind() - 从元素上删除一个以前附加事件处理程序

val()-获取匹配的元素集合中第一个元素的当前值

wrap()-在每个匹配的元素外层包上一个html元素

<!DOCTYPE html>
<html ><head lang="en">
    <meta charset="UTF-8">
  <script src="app/angular.min.js"></script>
 
</head>
<body id="app" ng-app="myApp" ng-controller="elementController">
    <button οnclick="toPage()" >点我1</button>

 <button ng-click="toAngu()" >点我2</button>



    <input type="text" ng-model="ttt" />
</body>
  <script type="text/javascript">
  	   function toPage() {
        angular.element(document.getElementById('app')).scope().toAngu();
    }
    angular.module("myApp",[])
    .controller("elementController", function($scope) {
    		$scope.ttt="前"
    		$scope.toAngu=function(){
    			console.log($scope.ttt) *a
			$scope.ttt="后"	
			console.log($scope.ttt)  ///*b
    		}
    })
  </script>
</html>
  蓝色部分,大家看完应该都懂,根据id 去获取 angular定义的方法。。。但是是间接的,通过非angular定义的方法去方法 angular的方法,所以 $scope.ttt 通过button1 改变的值 *b(后)的值不会被angular的 $watch监听到变化,所以页面的值不会变成“后”。通过button2改变的值,因为是ng-click直接访问angular定义的方法,所以会监听变化,页面的值跟着改变。。。  想表达的问题是,是否直接访问angular定义的属性方法,对应是否会监听其变化!。  附:若想通过 button1 做到双向绑定,则在 *b上 加上 “$scope.$apply()” 即可 但是button2会报错,因为直接访问angular不需要传播。

  Scope提供$watch()方法监视Model的变化。
Scope提供$apply()方法传播Model的变化。 



5.  angular.equals 和"==="和"=="

      http://www.92to.com/bangong/2016/09-24/10863700.html

此处转载一下上面的内容。

AngularJS中的angular.equals()方法用于比较两个对象、值或表达式是否相等。AngularJs文档中对equals方法比较的原则是这样描述的:

(1)比较的两个对象或值能够通过 === 表达式。===要求两个值不仅值相同,类型也要相同,也就是说,1 === “1”是不成立的,而1==‘1’成立

(2)比较的两个对象或值是相同类型的,而且它们所有的属性通过angular.equals()方法判断都是相等的。

(3)两个值都为(NaN)。(在JavaScript中认为NaN == NaN是false)

(4)两个值代表字面上相等的表达式,如两个正则表达式:/abc/与/abc/是相等的。

 

简单几个例子 就看懂了

	var a = 3;
    $scope.a_equals = angular.equals(a,3);// 相当于a === 3    输出 true

    var user1 = {"name":"xing","age":30};
    var user2 = {"name":"xing","age":30};
    $scope.user_equals = angular.equals(user1,user2);  //对象和里面的属性值都完全相同。 输出 true 


    $scope.nan_equals = angular.equals(NaN,NaN);//输出 true   但  in javascirpt is false   

    $scope.reg_equals = angular.equals(/abc/,/abc/);// 输出 true     但in javascript is false

6.  angular.extend

格式:angular.extends(obj1,ogj2,obj3...)方法的第一个参数是要被扩展的对象,后面可以传入一个或多个对象
把一个或多个对象中的方法和属性扩展到一个目的对象中,使得这个对象拥有其他对象相同的方法和属性。

<!-- 注意,这里obj1能修改其他对象obj对象的方法,由于extends()方法不是深复制的,obj1引用的是其他对象同一个对象,既obj1继承后修改了

对应的方法,那么原本的对象也跟着被修改了-->  

7.  angular.forEach

var objs=[{a:1},{a:2}];

angular.forEach(objs,function(data,index,array){

//data等价于array[index]

console.log(data.a+'='+array[index].a);

}


objs:需要遍历的集合

data:遍历时当前的数据

index:遍历时当前索引

array:需要遍历的集合,每次遍历时都会把objs原样的传一次。

             也可以不用写后面两个参数:


8.  angular.fromJson 和 angular.toJson

angular.fromJson()方法可以把一个Json字符串中解析成一个对象,或对象数组:

  var json = '{"name":"liSi", "password":"321"}';    json字符串
  var obj =  {  name:"liSi", password:"321" }        json对象
   angular.fromJson( json  )===obj  //true             字符串转对象
 angular.toJson(obj, true)===json;       对象转字符串

9.  angular.identity和angular.noop

转载http://www.cnblogs.com/pao8041/p/5888929.html

总的来说呢,这两个方法都是用来写函数的时候用的,根据上面写的demo的代码及运行结果来看,感觉他们的作用是用来防止函数传入的是null或者undefined或者其他不能操作的对象。因为如果去掉这两个后,你在函数调用的时候传入null/undefined/或者其他不能执行的对象,那么控制台是直接报错的...

 identity
function testCtrl() {
         var getResult = function (fn, val) {
          return (fn || angular.identity)(val);
      };
      var result = getResult(function (n) { return n * 2; }, 3); //  result = 6
      var null_result = getResult(null, 3);//  null_result = 3
      var undefined_result = getResult(undefined, 3);// undefined _result = 3
    };
noop

 function testCtrl() {
      var _console = function (v) {
          return v * 2;
      };
      var getResult = function (fn, val) {
          return (fn || angular.noop)(val);
      };
      var firstResult = getResult(_console, 3);//6
      var secondResult = getResult(null, 3);//undefined
      var thirdResult = getResult(undefined, 3);// undefined
    };



10. angular.injector$rootScope和$scope的概念和关联关系

       1.   $injector其实是一个IOC容器 ,包含了很多服务(类似于spring框架中的bean),其它代码能够过      $injector.get("serviceName")的方式,从injector中获取所需要的服务。详情参考 这篇文章

2、 scope是angularJS中的作用域(其实就是存储数据的地方),很类似javascript的原型链 。搜索的时候,优先找自己的scope,如果没有找到就沿着作用域链向上搜索,直至到达根作用域rootScope。

3、 $rootScope是由angularJS加载模块的时候自动创建的,每个模块只会有1个rootScope。rootScope创建好会以服务的形式加入到 $injector中。也就是说通过 $injector.get("$ rootScope ");能够获取到某个模块的根作用域。更准确的来说,$rootScope是由angularJS的核心模块ng创建的。

示例1:

// 新建一个模块
var module = angular.module("app",[]);

// true说明$rootScope确实以服务的形式包含在模块的injector中
var hasNgInjector = angular.injector(['app','ng']);  
console.log("has $rootScope=" + hasNgInjector.has("$rootScope"));//true

// 获取模块相应的injector对象,不获取ng模块中的服务
// 不依赖于ng模块,无法获取$rootScope服务
var noNgInjector = angular.injector(['app']);
console.log("no $rootScope=" + noNgInjector.has("$rootScope"));//false

// 获取angular核心的ng模块
var ngInjector = angular.injector(['ng']);  
console.log("ng $rootScope=" + ngInjector.has("$rootScope"));//true

上面的代码的确可以说明: $rootScope的确是由核心模块ng创建的,并以服务的形式存在于injector中 

如果创建injector的时候,指定了ng模块,那么该injector中就会包含$rootScope服务;否则就不包含$rootScope。

示例2:

<!doctype html>
<html lang="en">
	<head>
	   <meta charset="utf-8">
	   <script src="angular-1.2.25.js"></script>
	   <script>
	  
		var module = angular.module("app",[]);
		// 控制器里的$injector,是由angular框架自动创建的
		function FirstController($scope,$injector,$rootScope)
		{
			$rootScope.name="aty";
		}
		
		//自己创建了个injector,依赖于app和ng模块
		var myInjector = angular.injector(["app","ng"]);
		var rootScope = myInjector.get("$rootScope");
		alert(rootScope.name);//udefined
				
	   </script> 

	</head>
	
	<body ng-app="app">
		<div id="first" ng-controller="FirstController">
			<input type="text" ng-model="name">
			<br>
			{{name}}
		</div>	
	</body>
	
</html>

angular.injector()可以调用多次,每次都返回新建的injector对象 。所以我们自己创建的myInjector和angular自动创建的$injector不是同一个对象,那么得到的rootScope也就不是同一个。更详细的可以看 另一篇文章 中的



11. angular.isArray/isDate/isDefined/isElement/isFunction/isNumber/isObject/isString/isUndefined

isArray:是否数组                 isDate:是否日期         isDefined:是否已定义

isElement:是否元素            isFunction:是否函数           isNumber:是否数字 

isObject:是否对象                   isString: 是否字符串             isUndefined:是否未定义

举一例子:同12的例子。

12.angular.lowercase和angular.uppercase

	大小写转换 
 var lowercase = function (string) {
        return isString(string) ? string.toLowerCase() : string;
    };

    var uppercase = function (string) {
        return isString(string) ? string.toUpperCase() : string;
    };

  function isString(value) {
        return typeof value == 'string';
    }

13. angular.module

module是我们angular代码的入口,首先需要声明module,然后才能定义angular中的其他组件元素,如controller、service、filter、directive、config代码块、run代码块等。

关于module的定义为:angular.module(‘com.ngbook.demo’, [])。关于module函数可以传递3个参数,它们分别为:

  1. name:模块定义的名称,它应该是一个唯一的必选参数,它会在后边被其他模块注入或者是在ngAPP指令中声明应用程序主模块;
  2. requires:模块的依赖,它是声明本模块需要依赖的其他模块的参数。特别注意:如果在这里没有声明模块的依赖,则我们是无法在模块中使用依赖模块的任何组件的;它是个可选参数。
  3. configFn: 模块的启动配置函数,在angular config阶段会调用该函数,对模块中的组件进行实例化对象实例之前的特定配置,如我们常见的对$routeProvider配置应用程序的路由信息。它等同于”module.config“函数,建议用”module.config“函数替换它。这也是个可选参数。


  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用AngularJS制作一个购物车需要以下步骤: 1. 定义一个AngularJS app模块和controller控制器。 ```javascript var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { // 初始化购物车为空数组 $scope.cart = []; }); ``` 2. 在HTML中定义购物车的容器,并使用ng-repeat指令遍历购物车中的商品列表。 ```html <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="item in cart"> <div>{{item.name}}</div> <div>{{item.price}}</div> <div>{{item.quantity}}</div> <div>{{item.price * item.quantity}}</div> </div> </div> ``` 3. 在HTML中定义商品列表,并为每个商品添加一个“添加到购物车”的按钮。当用户点击按钮时,将该商品添加到购物车中。 ```html <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="product in products"> <div>{{product.name}}</div> <div>{{product.price}}</div> <button ng-click="addToCart(product)">添加到购物车</button> </div> <hr> <div ng-repeat="item in cart"> <div>{{item.name}}</div> <div>{{item.price}}</div> <div>{{item.quantity}}</div> <div>{{item.price * item.quantity}}</div> </div> </div> ``` 4. 在controller中实现addToCart()函数,用于将商品添加到购物车中。 ```javascript $scope.addToCart = function(product) { // 检查购物车中是否已存在该商品 var index = -1; for (var i = 0; i < $scope.cart.length; i++) { if ($scope.cart[i].name === product.name) { index = i; break; } } // 如果购物车中已存在该商品,则将商品数量加1 if (index !== -1) { $scope.cart[index].quantity++; } else { // 否则将商品添加到购物车中 $scope.cart.push({ name: product.name, price: product.price, quantity: 1 }); } }; ``` 这样就可以实现一个简单的购物车了。当然,你可以根据实际需求对代码进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明天你好丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值