angularjs使用文档

<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>

ng-directives

ng-app 指令

定义一个 AngularJS 应用程序

ng-app="myModule"

ng-model 指令

把元素值(比如输入域的值)绑定到应用程序 双向绑定

<input ng-model="name">
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
  • 为应用程序数据提供类型验证(number、email、required)。

    <form ng-app="" name="myForm">
        Email:
        <input type="email" name="myAddress" ng-model="text">
        <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
    </form>
    
  • 为应用程序数据提供状态(invalid、dirty、touched、error)。

    1. {{myForm.myAddress.$valid}} (如果输入的值是合法的则为 true)
    2. {{myForm.myAddress.$dirty}} (如果值改变则为 true)
    3. {{myForm.myAddress.$touched}} (如果通过触屏点击则为 true)
  • 为 HTML 元素提供 CSS 类。

    • ng-empty

    • ng-not-empty

    • ng-touched

      布尔值属性,表示用户是否和控件进行过交互,控件已失去焦点

    • ng-untouched

    • ng-valid

      布尔型属性,它指示表单是否通过验证。如果表单当前通过验证,他将为true

    • ng-invalid

    • ng-dirty

      控件输入值已变更

    • ng-pending

    • ng-pristine

      布尔值属性,控件为初始状态,表示用户是否修改了表单。如果为ture,表示没有修改过;false表示修改过

  • 绑定 HTML 元素到 HTML 表单

ng-bind 指令

把应用程序数据绑定到 HTML 视图

ng-init 指令

初始化 AngularJS 应用程序变量

通常情况下,不使用 ng-init。您将使用一个控制器或模块来代替它。

ng-repeat 指令

会重复一个 HTML 元素

ng-repeat="x in names"

ng-repeat 的循环对象是不能出现重复项的,在 循环后面加上 track by $index 就会解决问题,也就可以有重复对象了

<li ng-repeat="x in names track by $index">
  {{x}}.{{lastname}} 
  <button ng-click="delPerson($index)">删除</button> 
</li>  

ng-options

ng-option 指令来创建一个下拉列表,列表项通过对象和数组循环输出

<select ng-init="selectedName = names[0]" ng-model="selectedName" ng-options="x for x in names">
</select>

ng-options="y.brand for (x, y) in cars"

使用 ng-options 的选项是一个对象, ng-repeat 是一个字符串

相同效果

<select ng-model="selectedSite">
<option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option>
</select>
<select ng-model="selectedSite" ng-options="x.site for x in sites">
</select>

使用as指定下拉框的值

ng-options="y.url as x for (x, y) in sites"

as 前面的为下拉框的值,后面的为下拉框显示的内容

ng-disabled 指令

ng-show 指令

ng-hide 指令

ng-click 指令

自定义的指令

<body ng-app="myApp">

<runoob-directive></runoob-directive>

<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
    return {
        template : "<h1>自定义指令!</h1>"
    };
});
</script>

</body>
指令调用方式
  • 元素名

    <runoob-directive></runoob-directive>
    
  • 属性

    <div runoob-directive></div>
    
  • 类名

    <div class="runoob-directive"></div>
    
    app.directive("runoobDirective", function() {
        return {
            restrict : "C",
            template : "<h1>自定义指令!</h1>"
        };
    });
    
  • 注释

    <!-- directive: runoob-directive -->
    
    app.directive("runoobDirective", function() {
        return {
            restrict : "M",
            replace : true,
            template : "<h1>自定义指令!</h1>"
        };
    });
    
restrict 值
  • E 作为元素名使用
  • A 作为属性使用
  • C 作为类名使用
  • M 作为注释使用

restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令


AngularJS 应用

AngularJS 模块(Module)

定义了 AngularJS 应用。

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

“myApp” 参数对应执行应用的 HTML 元素。

AngularJS 控制器(Controller)

用于控制 AngularJS 应用。

控制器是 JavaScript 对象,由标准的 JavaScript 对象的构造函数 创建

ng-app指令指明了应用, ng-controller 指明了控制器。

<div ng-app="myApp" ng-controller="myCtrl">
 
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{firstName + " " + lastName}}
 
</div>
 
<script>
//定义应用
var app = angular.module('myApp', []);
//定义控制器
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>

Scope(作用域)

AngularJS 创建控制器时,你可以将 $scope 对象当作一个参数传递

app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";
});ngularJS 创建控制器时,你可以将 $scope 对象当作一个参数传递

scope 是一个 JavaScript 对象,带有属性和方法,这些属性和方法可以在视图和控制器中使用

<div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="name">
    <h1>{{greeting}}</h1>
    <button ng-click='sayHello()'>点我</button>    
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "Runoob";
    $scope.sayHello = function() {
        $scope.greeting = 'Hello ' + $scope.name + '!';
    };
});
</script>

根作用域$rootScope

可以作用在 ng-app 指令包含的所有 HTML 元素中

$rootScope 可作用于整个应用中。是各个 controller 中 scope 的桥梁。用 rootscope 定义的值,可以在各个 controller 中使用。

过滤器

转换数据

  1. {{ lastName | uppercase }} 大写

  2. {{ lastName | lowercase }} 小写

  3. {{ (quantity * price) | currency }} 货币

    {{ 250 | currency }}            // 结果:$250.00
    {{ 250 | currency:"RMB ¥ " }}  // 结果:RMB ¥ 250.00
    
  4. {{1490161945000 | date:“yyyy-MM-dd HH:mm:ss”}} //格式化

  5. filter查找

     // 查找name为iphone的行
    {{ [{"age": 20,"id": 10,"name": "iphone"},
    {"age": 12,"id": 11,"name": "sunm xing"},
    {"age": 44,"id": 12,"name": "test abc"}
    ] | filter:{'name':'iphone'} 
    }}  
    
  6. limitTo 截取

    {{"1234567890" | limitTo :6}} // 从前面开始截取6位
    {{"1234567890" | limitTo:-4}} // 从后面开始截取4位
    

添加参数

调用的时候用":参数" 的格式在后面追加

{{"jj" | myfilter:1:2:3:5}}

arguments取用参数

arguments为包含所有参数的对象

{"0":"jj","1":1,"2":2,"3":3,"4":5}

处理为参数数组

var newArguments= Array.prototype.slice.call(arguments);

返回所有拼接

return text+newArguments.join(',');

添加到指令

orderBy 过滤器根据表达式排列数

<li ng-repeat="x in names | orderBy:'country'">
  {{ x.name + ', ' + x.country }}
</li>

filter 过滤器从数组中选择一个子集

<ul>
  <li ng-repeat="x in names | filter:test | orderBy:'country'">
    {{ (x.name | uppercase) + ', ' + x.country }}
  </li>
</ul>

自定义过滤器

app.filter('reverse', function() { //可以注入依赖   
    return function(text) {       
    return text.split("").reverse().join("");    
    }
})

js过滤器用法

$scope.formatDate = $filter('date')(today, 'yyyy-MM-dd');

AngularJS 服务(Service)

服务是一个函数或对象,可在你的 AngularJS 应用中使用

$location 服务

可以返回当前页面的 URL 地址

app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});

$http 服务

服务向服务器发送请求,应用响应服务器传送过来的数据

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});

标准写法

// 简单的 GET 请求,可以改为 POST
$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
        // 请求成功执行代码
    }, function errorCallback(response) {
        // 请求失败执行代码
});

简写

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

$timeout 服务

对应了 JS window.setTimeout 函数

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
    $scope.myHeader = "Hello World!";
    $timeout(function () {
        $scope.myHeader = "How are you today?";
    }, 2000);
});

$interval 服务

对应了 JS window.setInterval 函数

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});

自定义服务

可以在控制器,指令,过滤器或其他服务中使用它

app.service('hexafy', function() {
  this.myFunc = function (x) {
    return x.toString(16);
  }
});
app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(255);
});
app.filter('myFormat',['hexafy', function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);

路由使用

引入文件

载入了实现路由的 js 文件:angular-route.js

定义依赖

angular.module('routingDemoApp',['ngRoute'])

ngView 指令

<div ng-view></div>

定义路由规则

        angular.module('routingDemoApp',['ngRoute'])
        .config(['$routeProvider', function($routeProvider){
            $routeProvider
            .when('/',{template:'这是首页页面'})
            .when('/computers',{template:'这是电脑分类页面'})
            .when('/printers',{template:'这是打印机页面'})
            .otherwise({redirectTo:'/'});
        }]);

依赖注入

value

Value 是一个简单的 javascript 对象,用于向控制器传递值(配置阶段)

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

// 创建 value 对象 "defaultInput" 并传递数据
mainApp.value("defaultInput", 5);
...

// 将 "defaultInput" 注入到控制器
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
   $scope.number = defaultInput;
   $scope.result = CalcService.square($scope.number);
   
   $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
   }
});

factory

一个函数用于返回值。在 service 和 controller 需要时创建。

定义factory

App.factory('MathService', function() {
   var factory = {};
   
   factory.multiply = function(a, b) {
      return a * b
   }
   return factory;
}); 

注入service

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

service

provider

AngularJS 中通过 provider 创建一个 service、factory等(配置阶段)

$provide.provider('MathService', function() {
      this.$get = function() {
         var factory = {};  
         
         factory.multiply = function(a, b) {
            return a * b; 
         }
         return factory;
      };
   });

constant

constant(常量)用来在配置阶段传递数值,注意这个常量在配置阶段是不可用的。

表格常用

循环实现列表

<table>
  <tr ng-repeat="x in names  | orderBy : 'Country'">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

添加单双行样式

table tr:nth-child(odd) {
  background-color: #f1f1f1;
}
table tr:nth-child(even) {
  background-color: #ffffff;
}

使用序号

<td>{{ $index + 1 }}</td>

使用单双行标志

<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>

表单常用

AngularJS 表单是输入控件的集合。

ng-model 指令

<input type="text" ng-model="firstname">

firstname 属性可以在 controller 中使用

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.firstname = "John";
});

也可以在应用的其他地方使用

<form>
First Name: <input type="text" ng-model="firstname">
</form>
 
<h1>You entered: {{firstname}}</h1>

Checkbox(复选框)

checkbox 的值为 true 或 false,可以使用 ng-model 指令绑定,它的值可以用于应用中

代码块中,myVar可无初始值

<form>
    Check to show a header:
    <input type="checkbox" ng-model="myVar">
</form>
 
<h1 ng-show="myVar">My Header</h1>

radio(单选框)

单选框使用同一个 ng-model ,绑定相同的值以判断选中项

<form>
    选择一个选项:
    <input type="radio" ng-model="myVar" value="dogs">Dogs
    <input type="radio" ng-model="myVar" value="tuts">Tutorials
    <input type="radio" ng-model="myVar" value="cars">Cars
</form>

select-option(下拉菜单)

<form>
  选择一个选项:
  <select ng-model="myVar">
    <option value="">
    <option value="dogs">Dogs
    <option value="tuts">Tutorials
    <option value="cars">Cars
  </select>
</form>

给定初始化信息

<select ng-model="myVar" ng-init="myVar='tuts'">
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值