angular简单了解


title:angular笔记

angular

  • 简介:

    • AngularJS 是一个 JavaScript 框架。它可通过 script 标签添加到 HTML 页面。AngularJS 通过 指令 扩展了 HTML,且通过表达式 绑定数据到 HTML。AngularJS 通过 ng-directives 扩展了 HTML。数据驱动视图
      1. ng-app 指令:定义一个 AngularJS 应用程序,指定程序的作用范围,一个网页中只能有一个 ng-app 指令
      1. ng-init 指令:应用程序中的模型数据(初始化应用程序中的变量) 现已不常用-控制器替代
      1. ng-bind 指令:将应用程序中的变量绑定到 html 元素的内容(与表达式{{}}作用相似)
      1. ng-model 指令:实现双向绑定 - 将输入的值绑定到应用程序中的变量
      1. ng-repeat 指令:对于集合中(数组中)的每个项会克隆一次 HTML 元素。
  • 优缺点:

    • AngularJS 非常结构化,大而全,坏处就是规定比较严格,好处是代码更一致,而且有一套很完善的测试流程支持。但是性能经常受人诟病。企业用户可能对性能没有那么敏感,反而喜欢这种写起来条理清晰,功能强大的框架。这有点像 Java,虽然臃肿,慢,但是成熟稳定,所以企业往往选择这样的框架
  • 模式:

    • AngularJS 应用采用 MV*模式:
      • View(视图), 即 HTML。
      • Model(模型), 当前视图中可用的数据。
      • ViewModel(视图模型),供在视图中展示用的。
    • 控制器是 JavaScript 对象,由标准的 JavaScript 对象的构造函数。
  • 核心思想: 依赖注入、模块化、双向绑定、语义化标签

  • 安装:

      1. webpack 相关配置
      1. 安装 angularJS
      • npm install angular --save
      1. 在主入口文件中引入 angular
      • import angular from ‘angular’
  • 内置事件指令: AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-。

    1. ng-change 指令:告诉 AngularJS 在 HTML 元素值改变时需要执行的操作
    2. ng-blur 指令:当 HTML 元素失去焦点时执行的表达式,需要搭配 ng-model 指令使用
    3. ng-submit 指令:表单提交后执行函数
    4. ng-click 指令:在 HTML 元素被点击后需要执行的操作
    5. ng-keydown 指令:在指定 HTML 元素上按下按键时需要的操作
    6. ng-keyup 指令:在指定 HTML 元素上按键松开时需要的操作
    7. ng-mousedown 指令:鼠标在指定的 HTML 元素上按下时要执行的操作
    8. ng-mouseenter:在鼠标指针穿过元素时执行表达式
    9. ng-mouseleave:在鼠标指针离开元素时执行表达式
    10. ng-mousemove:在鼠标指针在元素上移动时执行表达式
    11. ng-mouseover:在鼠标指针移动到元素上时执行表达式
    12. ng-mouseup:在鼠标指针在元素松开上时执行表达式
  • 内置节点的属性指令:

    1. ng-style 指定元素的 style 属性
    2. ng-class 指定 html 元素使用的 css 类
    3. ng-class-even 类似 ng-class,但只在偶数行起作用
    4. ng-class-odd 类似 ng-class,但只在奇数行起作用
    5. ng-show 显示或隐藏 HTML 元素,true 为显示
    6. ng-hide 隐藏或 html 元素,true 为隐藏
    7. ng-if 如果条件为 false 移除 HTML 元素
    8. ng-switch 规定显示或隐藏子元素的条件,对应的子元素使用
    9. ng-switch-when 指令,如果匹配则显示,其他没有匹配的则移除
    10. ng-src 指定 img 元素的 src 属性
    11. ng-href 为 a 标签元素指定链接,覆盖了 a 标签元素的 href 属性
  • 过滤器:

    • 可以用在指令和{{}}表达式中,用管道符号|隔开
    1. currency 格式化数字为货币格式,默认$,参数为货币符号
          <p>总价:{{num * price | currency}}</p>
          <p>总价:{{num * price | currency:'¥'}}</p>
      
    2. number 数值过滤器,默认保留 3 位小数,参数为小数位数
          <p>总价:{{num * price | number}}</p>
          <p>总价:{{num * price | number:4}}</p>
      
    3. orderBy 按属性排序,参数为属性名称 默认正序(a-z 或 1-n),倒序加"-"
          <p>{{city | orderBy:'eng'}}</p>
          <p>{{city | orderBy:'-eng'}}</p>
      
    4. date 格式化 date 到字符串
    5. filter 从 array 中选择一个条目子集,并作为一个新数组返回。
    • 过滤器实例:

      import angular from "angular";
      import "bootstrap/dist/css/bootstrap.min.css";
      import "./css/cart.css";
      
      const app = angular.module("app", []);
      
      app.controller("ctrl", [
        "$scope",
        "$filter",
        function(scope, $filter) {
          scope.cartList = [
            {
              proId: "1001",
              proName: "iphone5",
              num: 3,
              price: 2000
            },
            {
              proId: "1003",
              proName: "iphone7",
              num: 2,
              price: 4000
            },
            {
              proId: "1002",
              proName: "iphone6",
              num: 5,
              price: 3000
            }
          ];
          // scope.cartList = [];
          scope.account = "hhh";
          scope.url = "https://www.baidu.com/";
      
          // 排序的字段名
          scope.field = "";
      
          scope.paraStyle = {
            "background-color": "green",
            color: "#fff",
            "line-height": "40px",
            "padding-left": "5px"
          };
          scope.paraClass = "para";
          scope.imgUrl = "/static/img/cat.png";
          scope.img = "cat.png";
          scope.totalPrice = function() {
            let total = 0;
            // 通过js使用过滤器,在控制器注入一个$filter服务
            let newCartList = $filter("filter")(this.cartList, this.text);
            newCartList.map(item => {
              total += item.price * item.num;
            });
            return total;
          };
          scope.totalNum = function() {
            let total = 0;
            $filter("filter")(this.cartList, this.text).map(item => {
              total += item.num;
            });
            return total;
          };
      
          // 排序
          scope.orderAsc = function() {
            this.field = "price";
          };
      
          scope.orderDesc = function() {
            this.field = "-price";
          };
      
          // 日期
          scope.now = new Date();
      
          // 搜索内容
          scope.text = "";
        }
      ]);
      
  • 服务:

    • 在 AngularJS 中,服务是一个函数或对象。AngularJS 中可以创建自己的服务,或使用内置服务。
    1. $filter 服务(使用见过滤器实例)
    2. $location 服务
    3. $http 服务
          import angular form 'angular'
          angular.module('app',[]).controller('ctrl',['$scope','$http','$filter',function (scope,$http,$filter){
              scope.productList = [];
              // $http.get(url) 或 $http.post(url, data) 返回的是Promise对象
              $http.get('/static/data/xxx.json').then(resp=>{
                  console.log(resp);
                  scope.productList=resp.data;
              }).catch(error=>{
                  console.log(error);
              })
          }])
      
          import angular form 'angular'
          angular.module('app',[]).controller('ctrl',['$scope','$http','$filter',function (scope,$http,$filter){
              scope.productList = [];
              $http({
                  method:'get',
                  url:'/static/data/xxx.json'
              }).then(resp=>{
                  scope.productList=resp.data;
              }).catch(error=>{
                  console.log(error);
              })
          }])
      
  • 自定义模块:

    <div ng-app="app">
      <div ng-controller="productCtrl">
        <div ng-repeat="item in productList" class="col-sm-3 item">
          <img ng-src="/static/imgs/{{item.img}}" alt="" class="pro-img" />
          <div>
            <div class="col-sm-8">{{item.name}}</div>
            <div class="col-sm-4 text-right">{{item.price}}</div>
            <p class="text-right" style="padding: 15px;">{{item.sellnum}}</p>
          </div>
        </div>
      </div>
      <div ng-controller="cartCtrl"></div>
    </div>
    
    //product/product.module.js
    import angular from "angular";
    
    angular.module("product", []).controller("productCtrl", [
      "$scope",
      "$http",
      function(scope, http) {
        scope.productList = [];
        http
          .get("/static/data/product.json")
          .then(resp => {
            scope.productList = resp.data;
          })
          .catch(error => {
            console.log(error);
          });
      }
    ]);
    
    //cart/cart.module.js
    import angular from "angular";
    angular
      .module("cart", [])
      .controller("cartCtrl", ["$scope", function(scope) {}]);
    
        //index.js
        import angular from 'angular'
        //导入
        import './product/product.module.js'
        import './cart/cart.module.js'
        /* 创建模块:angular.module('模块名称', [依赖的模块])
        获得已有的模块:angular.module('模块名称')  */
        angular.module('app',['product','cart']);//创建模块并添加依赖模块
        ```
    
  • 路由:

    • 单页面应用(SPA)
    • 安装路由:npm install angular-route --save
    • 原理:通过添加路由标记来显示不同的内容
    • 导入:import ‘angular-route’
    • 创建:在创建模块时,添加依赖的路由模块
    • 配置路由:调用模块的 config 函数定义路由规则,注入$routrProvider
    • 实例:
    <div ng-app="app">
      <h1>淘宝</h1>
      <!-- 访问路由标记,根据不同的路由显示不同的页面视图 -->
      <a href="#!/login">亲,请登录</a>
      <!-- 路由标记匹配到的内容显示在 带有ng-view指令的元素中 -->
      <div ng-view></div>
    </div>
    
      import angular from 'angular'
      import 'angular-route'
      import './css/style.css'
      // 在创建模块时,添加依赖的路由模块
      const app = angular.module('app', ['ngRoute']);
    
      // 配置路由: 调用模块的config()函数定义路由规则, 注入$routeProvider
      app.config(['$routeProvider', function(provider){
          // 添加路由标记:以/开头,标记名称可以自定义
          provider.when('/login', {
              template: '<form><input type="text" placeholder="会员名/邮箱/手机号"/><input type="password" placeholder="密码"/><a href="#!/reg">免费注册</a></form>'
              // controller: ''
          }).when('/reg', {
              template: `<form>
              <label>手机号</label><input type="text"/>
              <label>密码</label><input type="password"/>
              <label>确认密码</label><input type="password"/>
              <input type="button" value="注册"/>
              </form>`
          }).when('/product', {
              template: '<div>这是首页</div>'
          }).when('/', {
              // 路由重定向
              // redirectTo: '/product'
              template: '<div>淘宝首页 <a href="#!/login">亲,请登录</a></div>'
          }).otherwise({
              template: '<p>您访问的页面不存在</p>'
          })
      }])
    
    • webpack处理html字符串
      • html文件转字符串:npm install html-loader --save–dev
      // html加载器:将html文件转成字符串
      {
        test: /\.html$/, use: {loader: 'html-loader'}
      }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值