温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用angularJs

发布时间:2020-08-24 15:19:55 来源:脚本之家 阅读:124 作者:Q的前端世界 栏目:web开发

本期更新,博主将给大家分享一些AngularJs常用的一些属性和方法,AngularJS 是由 Google 的员工 Miško Hevery 从 2009 年开始着手开发。这是一个非常好的构想,该项目目前已由 Google 正式支持,有一个全职的开发团队继续开发和维护这个库。AngularJS 是一个 JavaScript 框架。它是一个以 JavaScript 编写的库。因此,有一定JavaScript基础的朋友会更容易理解,其中的一些用法也可参照Javascript的使用方法。

一、AngularJS入门之指令与表达式

AngularJS 通过 指令 扩展了 HTML,且通过 表达式 绑定数据到 HTML。

【AngularJS常用指令】

1、ng-app:声明Angular所管辖的区域。一般写在body或html上,原则上一个页面只有一个;

<body ng-app=""></body>

2、ng-model:把元素值(比如输入域的值)绑定到应用程序的变量中。

<input type="text" ng-model="name"/>

3、ng-bind:把应用程序变量中的数据绑定到 HTML视图中。可用表达式{{ }}替代;

<div ng-bind="name"></div>
<div>{{name}}</div>

4、ng-init:初始化 AngularJS应用程序中的变量。

<body ng-app="" ng-init="name=123">

5、表达式: {{}} 绑定表达式,可以包含文字、运算符和变量。但表达式在网页加载瞬间会看到{{}},所以可以用ng-bind=""替代

{{ 5 +""+ 5 + ',Angular'}}

【基本概念】

1、指令:AngularJS中,通过扩展HTML的属性提供功能。所以,ng-开头的新属性,被我们成为指令

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>AngularJS入门</title>
 </head>
<body ng-app="" ng-init="name=123">

  <input type="text" id="input" ng-model="name"/>
  <div id="div" ng-bind="name+',Angular'">{{name}}</div>

  <input type="text" id="input2" ng-model="name"/>

  <p>我的第一个表达式: {{ 5 +""+ 5 + ',Angular'}}</p>

 </body>

 <script src="libs/jquery-3.1.1.js"></script>
 <script src="libs/angular.js"></script>

 <script type="text/javascript">
//  var input1 = document.getElementById("input");
//  var div = document.getElementById("div");
//  
//  input1.onkeyup = function(){
//   div.innerHTML = input1.value;
//  }

//  $("#input").keyup(function(){
//   $("#div").html($("input").val());
//  });
 </script>
</html>

二、AngularJS中的MVC与作用域

[MVC三层架构]

1、Model(模型):应用程序中用于处理数据的部分。(保存或修改数据到数据库、变量等)。AngularJS中的Model特指的是:数据

View(视图):用户看到的用于显示数据的页面;

Controller(控制器):应用程序中处理用户交互的部分。负责从视图读取数据,控制用户输入,并向模型发送数据。

2、工作原理: 用户从视图层发出请求,controller接收到请求后转发给对应的model处理,model处理完成后返回结果给controller,并在view层反馈给用户。

主要用于CRUD类应用,不适合游戏开发和DOM操作

创建一个Angular模块,即ng-app所绑定的部分,需传递两个参数:

① 模块名称,即ng-app所需要绑定的名称。ng-app="myApp"

② 数组:需要注入的模块名称,不需要可为空。

var app = angular.module("myApp",[]);

在Angular模块上,创建一个控制器Controller,需要传递两个参数

① Controller名称,即ng-controller需绑定的名称。ng-controller="myCtrl"

② Controller的构造函数:构造函数可以传入多个参数,包括$scope/$rootScope以及各种系统内置对象;

[AngularJS中的作用域]

$scope:局部作用域,声明在$scope上的属性和方法,只能在当前Controller中使用;

$rootScope:根作用域,声明在$rootScope上的属性和方法,可以在ng-app所包含的任何区域使用(无论是否同一Controller,或是否在Controller包含范围中)。

>>> 若没有使用$scope声明变量,而直接在html中使用ng-model绑定的变量作用域为:

1.如果ng-model在某个ng-controller中,则此变量会默认绑定到当前Controller的$scope上;

2.如果ng-model没有在任何一个ng-controller钟,则此变量将绑定在$rootScope上;

app.controller("myCtrl",function($scope,$rootScope){
//$scope.name = "name1";
$rootScope.age = 14;
$scope.classes = {
name:"H51701",
num:"33"
};
});
app.controller("myCtrl1",function(){
});

三、Angular过滤器

AngularJS中,过滤器可以使用一个管道字符(|)添加到表达式和指令中。

>>> 系统内置过滤器:

currency 格式化数字为货币格式。

filter 从数组项中选择一个子集。

lowercase 格式化字符串为小写。

orderBy 根据某个表达式排列数组。

uppercase 格式化字符串为大写。

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="css/bootstrap.css" rel="external nofollow" />
 </head>

 <body ng-app="app" ng-controller="ctrl">

  <p>{{"aBcDeF"|uppercase}}</p>
  <p>{{"aBcDeF"|lowercase}}</p>
  <p>{{123456|currency}}</p>
  <form class="form-horizontal">

  </form>
  <div class="form-group">
   <label>请输入筛选信息:</label>
   <input type="text" ng-model="search" />
  </div>

  <table class="table table-bordered">
   <thead>
    <tr>
     <th>姓名</th>
     <th>年龄</th>
     <th>成绩</th>
    </tr>
   </thead>
   <tr ng-repeat="item in classes| filter:search | orderBy:'score'">
    <td>{{item.name}}</td>
    <td>{{item.age}}</td>
    <td>{{item.score}}</td>
   </tr>
  </table>

  <p>{{"123456"|reverse}}</p>

 </body>
 <script src="libs/angular.js"></script>
 <script>

  angular.module("app",[])
  .controller("ctrl",function($scope){
   $scope.classes = [
    {name:"张二",age:"12",score:"88"},
    {name:"张三",age:"12",score:"88"},
    {name:"李四",age:"15",score:"78"},
    {name:"李五",age:"15",score:"78"},
    {name:"王大麻子",age:"18",score:"98"},
    {name:"王二麻子",age:"18",score:"98"}
   ];

  })
  /*
   * 自定义过滤器
   */
  .filter('reverse', function() {

   return function(text) {
    if(!angular.isString(text)){
     return "您输入的内容不是字符串";
    }else{
     return text.split("").reverse().join("");
    }

   }
  })
 </script>
</html>

四、Angular服务Service

【服务Service】

1、内置服务:

>>>使用内置服务必须在controlller中通过函数的参数注入进来!!!!

$location :返回当前页面的 URL 地址;

$http: 服务器请求数据,类似于AJax;

$timeout :对应了 JS window.setTimeout 函数。

$interval :对应了 JS window.setInterval 函数。

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
 </head>
 <body ng-app="app" ng-controller="ctrl">
  <pre >{{local}}</pre>
  <p ng-bind="myHeader"></p>
  <p ng-bind="num"></p>
  <p >{{gongneng}}</p>
  <p>将255转为16进制:{{hexafy}}</p>
  <p>{{123|filt}}</p>

  <p>{{123|filt1}}</p>

 </body>
 <script type="text/javascript" src="libs/angular.js" ></script>
 <script type="text/javascript">

  angular.module("app",[])
  .controller("ctrl",function ($scope,$location,$timeout,$interval,$hexafy) {
   $scope.local=$location.absUrl();
    $scope.myHeader = "Hello World!";
   $timeout(function () {
    $scope.myHeader = "How are you today?";
   }, 2000);
   $scope.num=0;
   $interval(function () {
    $scope.num++;
   },1000);

   $scope.gongneng=$hexafy.$$gongneng;
   $scope.hexafy=$hexafy.myFunc(255);
  })
  /*自定义服务*/
  .service('$hexafy', function() {
   this.$$gongneng = "将转入的数字,转为16进制";
   this.myFunc = function (x) {
    return x.toString(16);
   }
  })
  .filter("filt",function(){
   return function(x){
    return x.toString(16);
   }
  })
  /*在过滤器中,调用自定义服务*/
  .filter("filt1",function($hexafy){
   return function(x){
    return $hexafy.myFunc(x);
   }
  })
 </script>
</html>

【自定义服务factory】

factory 是一个函数用于返回值,通常我们使用 factory 函数来计算或返回值。(factory使用上,与service差距不大)

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="libs/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
 </head>

 <body ng-app="app" ng-controller="ctrl">
  <p>
   [功能]<br/>
   {{gongneng}}
  </p>
  <p>
   255转成16进制为:{{num}}
  </p>
 </body>
 <script src="libs/angular.js"></script>
 <script>

  angular.module("app",[])
  .config()
  .controller("ctrl",function($scope,hexafy){
   $scope.gongneng = hexafy.gongneng;
   $scope.num = hexafy.myFunc(255);
  })
  .factory('hexafy',function(){
   var obj = {
    gongneng : "将转入的数字,转为16进制",
    myFunc:function(x){
     return x.toString(16);
    }
   };
   return obj;
  })
 </script>
</html>

【自定义服务provide】

1、在AngularJS中,Service,factory都是基于provider实现的。

2、在provider中,通过$get()方法提供了factory的写法,用于返回 value/service/factory。;

3、provider是三种自定义服务中,唯一可以写进config配置阶段的一种。

如果服务,必须要在配置阶段执行,那么必须使用provider。否则,一般使用Service或factory

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="libs/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
 </head>

 <body ng-app="app" ng-controller="ctrl">
  <p>
   [功能]<br/>
   {{gongneng}}
  </p>
  <p>
   255转成16进制为:{{num}}
  </p>
 </body>
 <script src="libs/angular.js"></script>
 <script>

  angular.module("app",[])
  /*在配置阶段声明procide服务!*/

  .controller("ctrl",function($scope,hexafy){
   $scope.gongneng = hexafy.gongneng;
   $scope.num = hexafy.myFunc(255);
  })

  /*定义一个provider服务*/
  .provider('hexafy',function(){
//   this.gongneng = "将转入的数字,转为16进制";
   this.$get = function(){
    var obj = {
     gongneng : "将转入的数字,转为16进制",
     myFunc : function(x){
      return x.toString(16);
     }
    }
    return obj;
   }
  })
 </script>
</html>

五、Angular中的$http

$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="libs/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
 </head>

 <body ng-app="app" ng-controller="ctrl">
  <!--<pre>
   {{data}}
  </pre>-->
  <div class="container" >
  <div class="panel panel-primary" >
   <div class="panel-heading">
    <div class="panel-title" >H5-1701班级信息表</div>
   </div>
   <div class="panel-body">
    <table class="table table-bordered">
     <thead>
      <tr>
       <th>姓名</th>
       <th>年龄</th>
       <th>爱好</th>
       <th>语文成绩</th>
       <th>数学成绩</th>
       <th>总分</th>
      </tr>
     </thead>
     <tr ng-repeat="item in data | orderBy:'score.chinese + score.math'">
      <td ng-bind="item.name"></td>
      <td ng-bind="item.age"></td>
      <td ng-bind="item.hobby">
      <!--<span ng-repeat="a in item.hobby">{{a}}</span>-->
      </td>
      <td ng-bind="item.score.chinese"></td>
      <td ng-bind="item.score.math"></td>
      <td ng-bind="item.score.chinese + item.score.math"></td>
     </tr>
    </table>
   </div>
  </div>
  </div>

 </body>
 <script src="libs/angular.js"></script>
 <script>

  angular.module("app",[])
  .controller("ctrl",function($scope,$http){

   $http.post('h61701.json',{/*传递的参数对象*/})
   .then(function(res){
    $scope.data = res.data;//data 从返回的信息中,取出需要的数据。为JSON对象(数组)
   });

  })
 </script>
</html>

六、Angular中的select

使用数组作为数据源。

其中,x表示数组的每一项。

默认会将x直接绑定到option的value中。

而option显示的内容,有前面的x for... 决定

<select ng-model="name" ng-options="x.site for x in sites">
  </select>

使用对象作为数据源.

其中,(x,y)表示键值对,x为键,y为值。

默认会将值y绑定到option的value中.

而option显示的内容,有前面的x for... 决定

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="libs/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
  <style type="text/css">
   *{
    margin: 10px;
   }
  </style>
 </head>

 <body ng-app="app" ng-controller="ctrl">

  <select ng-model="name" ng-options="x for (x, y) in sites">
  </select>

  <div class="alert alert-info" >
   您选择的是:{{name}}
  </div>

  <table class="table table-bordered">
   <tr>
    <th>序号</th>
    <th>姓名</th>
   </tr>
   <tr ng-repeat="item in options">
    <td>{{$index +1}}</td><!--$index 表示遍历的索引,从0开始-->
    <td>{{item}}</td>
   </tr>
  </table>

 </body>
 <script src="libs/angular.js"></script>
 <script>

  angular.module("app",[])
  .controller("ctrl",function($scope){
   $scope.options = ["张三","李四","王二麻子","杰小瑞"];

   $scope.sites = {
    site01 : "Google",
    site02 : "Runoob",
    site03 : "Taobao"
   };

  })
 </script>
</html>

七、Angular中的DOM与事件

ng-disabled="true/false" 当传入true时,控件禁用。传入false是,启用;

ng-show 默认隐藏 传入true时显示;

ng-hide 默认显示 传入true是隐藏;

ng-click定义了AngularJS中的点击事件。

只能触发绑定在Angular作用域中的属性与方法。

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="libs/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
  <style type="text/css">
   *{
    margin: 10px;
   }
  </style>
 </head>

 <body ng-app="app" ng-controller="ctrl">

   <input type="checkbox" ng-model="mySwitch">是否同意我是帅哥!
  </label>

  <button ng-disabled="!mySwitch" class="btn btn-primary">点我!</button>
  <p></p>

  <label>
   <input type="checkbox" ng-model="mySwitch2">是否显示?
  </label>

  <button ng-show="mySwitch2" class="btn btn-primary">点我!</button>
  <p></p>

  <label>
   <input type="checkbox" ng-model="mySwitch3">是否隐藏?
  </label>

  <button ng-hide="mySwitch3" class="btn btn-primary">点我!</button>
  <p></p>

  <button ng-click="count = count + 1">点我!</button>
  <p>{{ count }}</p>
  <button ng-click="func()">说一下感想吧!</button>

 </body>
 <script src="libs/angular.js"></script>
 <script>

  angular.module("app",[])
  .controller("ctrl",function($scope,$rootScope){
   $scope.count = 10;
   $scope.func = function(){
    alert("我弹了一个窗!");
   }
  })
 </script>
</html>

八、Angular表单和输入验证

[AngularJS中的表单验证]

1、表单中,常用的验证操作:

$dirty 表单有填写记录

$valid 字段内容合法的

$invalid 字段内容是非法的

$pristine 表单没有填写记录

$error 表单验证不通过的错误信息

2、验证时,需给表单,及需要验证的input,设置name属性:

给form及input设置name后,会将form表单信息,默认绑定到$scope作用域中。故,可以使用 formName.inputName.$验证操作 得到验证结果:

例如:formName.inputName.$dirty = "true" 表单被填写过

formName.inputName.$invalid = "true" 表单输入不合法

formName.inputName.$error.required = "true" 表单必填但未填

$error支持的验证有:required/minlength/maxlength/pattern/email/number/date/url等。。。

3、为避免冲突,例如使用type="email"时,H5也会进行验证操作。如果只想使用AngularJS验证,可以使用<form novalidate></form>属性,禁用H5自带验证功能;

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="libs/bootstrap.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" />
  <style type="text/css">
   .row{
    margin-bottom: 10px;
   }
   .row .col-xs-5{
    text-align: center;
   }
   .suc{
    border-color: #3c763d;
     -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
      box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
   }
   .suc:focus{
    border-color: #2b542c;
 -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
   box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
   }

   .err{
    border-color: #a94442;
 -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
   box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
   }
   .err:focus{
    border-color: #843534;
 -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
   box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
   }
  </style>
 </head>
 <body ng-app="app" ng-controller="ctrl">
 <div class="container" >
  <div class="panel panel-primary">
   <div class="panel-heading">
    <div class="panel-title" >
     用户注册
    </div>
   </div>

   <div class="panel-body">
    <form action="" method="get" class="form-horizontal" name="myForm" novalidate>
    <div class="row" >
     <div class="col-xs-3">
      用户名:
     </div>
     <div class="col-xs-9">
      <input type="text" class="form-control" ng-model="user.name" name="name" ng-minlength="4" ng-maxlength="10" required ng-class="{suc:myForm.name.$valid && myForm.name.$dirty,err:myForm.name.$invalid && myForm.name.$dirty}"/>
      <p  ng-show="myForm.name.$invalid && myForm.name.$dirty">
       <!--当有填写记录且不合法时,p显示-->
       <span ng-show="myForm.name.$error.required">用户名必须填写!!!</span>
       <span ng-show="myForm.name.$error.minlength">用户名最少包含4个字符!!!</span>
       <span ng-show="myForm.name.$error.maxlength">用户名最多包含10个字符!!!</span>
      </p>
     </div>
    </div>

    <div class="row">
     <div class="col-xs-3">
      邮箱:
     </div>
     <div class="col-xs-9">
      <input type="email" class="form-control" ng-model="user.mail" name="mail" required ng-class="{suc:myForm.mail.$valid && myForm.mail.$dirty,err:myForm.mail.$invalid && myForm.mail.$dirty}"/>
      <p  ng-show="myForm.mail.$invalid && myForm.mail.$dirty">
       <!--当有填写记录且不合法时,p显示-->
       <span ng-show="myForm.mail.$error.required">邮箱必须填写!!!</span>
       <span ng-show="myForm.mail.$error.email">邮箱格式不合法!!!</span>
      </p>
     </div>
    </div>

    <div class="row">
     <div class="col-xs-3">
      密码:
     </div>
     <div class="col-xs-9">
      <input type="password" class="form-control" ng-model="user.pwd" name="pwd" pattern="^\w{6,18}$" required ng-class="{suc:myForm.pwd.$valid && myForm.pwd.$dirty,err:myForm.pwd.$invalid && myForm.pwd.$dirty}"/>
      <p  ng-show="myForm.pwd.$invalid && myForm.pwd.$dirty">
       <!--当有填写记录且不合法时,p显示-->
       <span ng-show="myForm.pwd.$error.pattern">密码应为6-18位,且只能为字母、数字、下划线</span>
      </p>
     </div>

    </div>

    <div class="row">
     <div class="col-xs-3">
      确认密码:
     </div>
     <div class="col-xs-9">
      <input type="password" class="form-control" ng-model="rePwd" name="rePwd" required ng-class="{suc:myForm.rePwd.$dirty&&rePwd==user.pwd,err:myForm.rePwd.$dirty&&rePwd!=user.pwd}"/>
      <p  ng-show="myForm.rePwd.$dirty && rePwd!=user.pwd">
       <!--当有填写记录且不合法时,p显示-->
       两次密码输入不一致!!!
      </p>
     </div>
    </div>

    <div class="row">
     <div class="col-xs-5">
      <input type="submit" value="注册" class="btn btn-success" ng-disabled="myForm.$invalid || rePwd!=user.pwd" />
     </div>
     <div class="col-xs-5">
      <input type="button" value="重置" class="btn btn-warning" ng-click="resets()" />
     </div>
    </div>
    </form>
   </div>
  </div>
  <pre>
   {{user.pwd}}
  </pre>
 </div>

 </body>
 <script src="libs/angular.js"></script>
 <script>

   $scope.resets = function(){
    $scope.user = angular.copy($scope.initUser);
   }
   $scope.resets();
  })
 </script>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持亿速云!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI