zoukankan      html  css  js  c++  java
  • angular.js 例子

    angular.js是一个前端的MVC框架,12年的时候曾近在一个portal平台的项目中使用过。

    下面给出一个angular.js的典型例子,涵盖一些基础的知识点,用以复习备忘:

    <html ng-app = "myapp" >
    <head>
      <script src="angular.js"></script>
    </head>
    <!--ng-controller 定义body内使用该控制器 -->
    <body ng-controller="userlist">
    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span2">
          <!--ng-model 定义数据模型 -->
          Search: <input ng-model="key">
    
        </div>
        <div class="span10">
          <ul>
            <!--filter 实现过滤 -->
            <li ng-repeat="user in users | filter:key">
              <user name = 'fredric'></user>
            </li>
          </ul>
    
           </div>
      </div>
    </div>
    
    <script>
    //使用模块
    var app = angular.module("myapp", []);
    
    //自定义指令
    app.directive('user', function() {
       var directive = {};
       directive.restrict = 'E';
       directive.template = "name: <b>{{user.name}}</b> , password: <b>{{user.password}}</b>";
       
       return directive;
    });
    
    //定义服务
    app.factory('encrypt', function() {     
       var factory = {};  
       factory.encrypt01 = function(password) {
          return '***********'; 
       }
       return factory;
    }); 
    
    //定义控制器
    app.controller("userlist", function($scope, $http, encrypt) {
    $http.get("http://localhost:3000/test")
        .success(function(response) {
        
        //使用服务
        for(var i = 0; i < response.length; i++){
            response[i].password = encrypt.encrypt01(response[i].password);
        } 
        
        $scope.users = response;
        });
    });
     </script>
    
    </body>
    </html>

    总结:

    我认为用面向对象的工程来理解angular.js会更加容易:

      ng-app:定义模块化,其中value和constent定义这个模块的全局变量,在module方法里描述这个模块的依赖(包含哪些服务、控制器等);

      ng-controller:描述这个模块中的不同的类,controller本身类似这个类的构造函数,ng-model是这个类的成员,$scope可以理解为this指针;

      ng-directive:理解为UI widget;

      service:不同类(controller)之间的公共方法,类似utils模块;

      html:原本的html变为了视图,通过model即指令,呈现出模板的概念;

    其他诸如filter oute等,我觉得都可以理解成为一些小的特性库,对整个angular.js的架构无伤大雅。

  • 相关阅读:
    bootstrap收费模版,里面也有后台模版
    漂亮的后台设计
    table ie td宽度 bug
    何让WordPress博客首页不显示某分类的所有文章?
    WordPress不同分类使用不同列表样式
    wordpress学习笔记(一)
    Chariot主题是一款专业自适应Wordpress作品主题
    洛谷P1450 [HAOI2008]硬币购物 动态规划 + 容斥原理
    洛谷P2671 求和 数学 前缀和
    洛谷1288 取数游戏II 博弈论
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/4465790.html
Copyright © 2011-2022 走看看