带你走入angular--angular入门(二、基础知识点)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29326717/article/details/79650634

1、AngularJS 表达式

写在双大括号内:{{ expression }} ,把数据绑定带 HTML,与ng-bind指令相似。在书写的位置“输出”数据,可以包含文字、运算符和变量。

把数据绑定带 HTML,使用 ng-init 的情况较少,表达式不支持条件判断、循环及异常,但支持过滤。

注:ng-app是一个特殊指令:一个HTML文档只出现一次,若出现多个,第一个起作用;其值可为空(练习),项目中一定要赋值。

2、AngularJS 指令

通过指令扩展HTML,带前缀ng-。内置指令为应用添加功能,允许自定义指令。

ng-repeat指令 --> 对于集合中(数组中)的每一项会克隆一次HTML元素。

AngularJS支持数据库的CRUD(增加Create、读取Read、更新Update、删除Delete)应用程序。

ng-app --> 定义应用程序根元素。网页加载完毕时自动引导(自动初始化)应用程序。

ng-init --> 定义初始值,一般不用,一般用控制器或模块代替它。

ng-model --> 绑定HTML元素到应用程序数据。可为应用程序数据提供验证(number、email、required),可为应用程序数据提供状态(invalid、dirty、touched、error)。为HTML元素提供CSS类。绑定HTML元素到HTML表单。

创建自定义指令 --> 可用 .directive 函数来添加自定义的指令。要调用自定义指令,HTML元素上需要添加自定义指令名。可通过元素名、属性、类名、注释来调用指令。restrict 值可是一下几种:E-作为元素名使用;A-作为属性使用;C-作为类名使用;M-作为注释使用;其默认值为EA。

.html

<div ng-app="app">
    <hello></hello>
    <div hello></div>
    <div class="hello"></div>
    <div hello class="jike"></div>
</div>

.js

var app = angular.module('app',[]);
app.directive('hello', function(){
    return {
        restrict: 'E',
        replace: true, // 替换到我们自定义的 directive 的名称
        template: '<div>Hello Angular!</div>',
    };
});
app.directive('hello', function(){
    return {
        restrict: 'A',
        link: function(){
            alert('我在这...');
        }
    };
});
app.directive('jike', function(){
    return {
        restrict: 'C',
        link: function(){
            alert('啊哈~');
        }
    };
});

 

3、AngularJS ng-model指令:

ng-model 用于绑定应用程序数据到HTML控制器(input、select、textarea)的值。可将输入域的值与AngularJS创建的变量绑定。

双向绑定 --> 在修改输入域的值时,AngularJS属性值也将修改。

验证用户输入:

<form ng-app="" name="myForm">
    Email:<input type="email" name="myAddress" ng-model="text">
    <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
</form>

提示信息会在 ng-show 属性返回 true 时提示。

应用状态:ng-model 可为应用数据提供状态值(invalid、dirty、touched、error)。

<form ng-app="" name="myForm" ng-init="myText='[email protected]'">
    Email:<input type="email" name="myAddress" ng-model="myText" required>
    <p>编辑邮箱地址,查看状态的改变。</p>
    <h1>状态</h1>
    <p>Valid:{{ myForm.myAddress.$valid }}</p><!-- 输入合法则为true  -->
    <p>Dirty:{{ myForm.myAddress.$dirty }}</p><!-- 值改变则为true  -->
    <p>Touched:{{ myForm.myAddress.$touched}}</p><!-- 通过触屏点击则为true  -->
</form>

CSS类:

ng-model指令基于它们的状态为HTML元素提供了CSS类。

ng-model指令根据表单域的状态添加/移除以下类:

    ng-empty

    ng-not-empty

    ng-touched --> 用户是否和控件进行交互

    ng-untouched --> 控件未失去焦点

    ng-valid --> 通过验证

    ng-invalid --> 未通过验证表单

    ng-dirty--> 是否修改了表单。

    ng-pending --> 任何为满足 $asyncValidators 的情况。

    ng-pristine --> 用户是否修改了表单,true --> 没修改,false --> 修改了。(控件为初始状态)

    ng-valid-[key] --> 由 $setValidity 添加的所有验证通过的值。

    ng-invalid-[key] --> 有 $setValidity 添加的所有验证失败的值。

 

4、AngularJS Scope(作用域)

Scope(作用域)是应用在HTML(视图)和JavaScript(控制器)之间的纽带。

Scope是一个对象,有可用的方法和属性。

Scope可应用在视图和控制器上。

创建控制器时,可将 $scope 对象当做参数传递。

AngularJS应用组成:

    View(视图) --> 即HTML

    Model(模型) --> 当前视图中可用的数据

    Controller(控制器) --> 即JavaScript函数,可添加或修改属性

scope是模型、JavaScript对象、有属性和方法。

<div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="name">
    <h1>{{ greeting }}</h1>
    <buton ng-click="sayHello()">点我</buton>
</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中使用。

<div ng-app="myApp" ng-controller="myCtrl">
    <h1>{{ lastname }}家族成员:</h1>
    <ul>
        <li ng-repeat="x in names">{{x}} {{lastname}}</li>
    </ul>
</div>
<script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl', function($scope, $rootScope){
        $scope.name = ['Emil','Tobias','Linus'];
        $rootScope.lastname= 'Refsnes';
    });
</script>

$rootScope:设置的变量在所有controller里面都是可以直接用 {{ $root.变量名 }} 来显示,也可赋值给 $scope。

$rootScope:全局对象的属性可在所有子作用域中访问,子作用域互相无法访问对方私有属性。

 

5、AngularJS 控制器

控制器应用程序的数据,常见的JavaScript对象

ng-controller

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

AngularJS使用 $scope 对象来调用控制器

在AngularJS中,$scope 是一个应用对象(属于应用变量和函数)

控制器的 $scope (相当于作用域、控制范围)用来保存 AngularJS Model(模型)的对象

控制器方法:控制器也可以有方法(变量和函数)

6、AngularJS 过滤器

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

可用于转换数据:

    currency --> 格式化数字为货币格式

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

    lowercase --> 格式化字符串为小写

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

    uppercase --> 格式化字符串为大写

过滤器可以通过一个管道字符(|)和一个过滤器添加到表达式中、指令中

{{ lastName | uppercase }}
{{ lastName | lowercase }}
{{ (quantity * price) | currency }}
<li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ',' + x.country}}
</li>

过滤输入:输入过滤器可以通过一个管道字符(|)和一个过滤器添加到指令中,该过滤器后跟一个冒号和模型名称。

<div ng-app="myApp" ng-controller="namesCtrl">
    <p><input type="text" ng-model="test"></p>
    <ul>
        <li ng-repeat="x in names | filter:test | orderBy:'country'">
            {{ (x.name | uppercase) + ',' + x.country }}
        </li>
    </ul>
</div>

自定义过滤器:

<div ng-app="myApp" ng-controller="myCtrl">
    姓名:{{ msg | reverse }}
</div>
<script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl', function($scope){
        $scope.msg = 'Runoob';
    });
    app.filter('reverse', function(){
        return function(text){
            // .reverse() js方法,用于颠倒数组中元素的顺序
            // .join() js方法,把数组中的所有元素放入一个字符串
            return text.split("").reverse().join("");
        };
    });
</script>

date格式化:

{{ 1490161945000 | date:'yyyy-MM-dd HH:mm:ss' }} //2017-03-22 13:52:25

number格式化(保留小数):

{{ 149016.1945000 | number:2 }}

currency货币格式化:

{{ 250 | currency }} //$250.00
{{ 250 | currency:"RMB ¥" }} //RMB ¥250.00

filter查找:

{{ [
    {"age":20,"id":10, "name":"iphone"},
    {"age":12,"id":11, "name":"sunmXing"},
    {"age":44,"id":12, "name":"test abc"},
    ] | filter:{'name':'iphone'} 
}} 

limitTo截取:

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

orderBy排序:

// 根据 id 降序
{{ [
    {"age":20,"id":10, "name":"iphone"},
    {"age":12,"id":11, "name":"sunmXing"},
    {"age":44,"id":12, "name":"test abc"},
    ] | orderBy:'id':true
}} 
// 根据 id 升序
{{ [
    {"age":20,"id":10, "name":"iphone"},
    {"age":12,"id":11, "name":"sunmXing"},
    {"age":44,"id":12, "name":"test abc"},
    ] | orderBy:'id'
}} 

7、AngularJS 服务(service)

在AngularJS 中,服务是一个函数或对象,内建了30多个服务,有个$location服务,可返回当前页面的URL地址。

注:$location服务是作为一个参数传递到controller中,如果要使用它,需要在controller中定义。

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

$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 函数。

创建自定义服务:在定义控制器时独立添加,设置依赖关系。

<div ng-app="myApp" ng-controller="myCtrl">
    <p>255的16进制是:</p>
    <h1>{{ hex }}</h1>
</div>
<script>
    var app = angular.module('myApp',[]);
    app.service('hexafy', function(){
        this.myFunc = function(x){
            return x.toString(16);
        };
    });
    app.controller('myCtrl', function($scope, $timeout){
        $scope.hex = hexafy.myFunc(255);
    });
</script>

过滤器中,使用自定义服务:

app.filter('myFormat', ['hexafy', function(hexafy){
    return function(x){
        return hexafy.myFunc(x);
    };   
}]);

 

8、AngularJS XML HttpRequest

$http --> 用于读取远程服务器的数据。

使用格式:

$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);

$http.get

$http.post

$http.head

$http.put

$http.delete

$http.jsonp

$http.patch

$http.get(url) --> 用于读取服务器数据的函数。

 

9、AngularJS select(选择框)

可用数组或对象创建一个下拉列表选项。

使用ng-option创建选择框。

<div ng-app="myApp" ng-controller="myCtrl">
    <select ng-init="selectedName=names[0]" ng-model="selectedName" ng-option="x for x in names"></select>
</div>
<script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl', function($scope){
        $scope.names = ["Google","Runoob","Taobao"];
    });
</script>

用ng-repeat创建下拉列表

<select>
    <option ng-repeat="x in names">{{ x }}</option>
</select>

ng-options --> 选择的值是一个对象

ng-repeat --> 有局限,选择的是一个字符串

使用对象作为数据源,x为键(key),y为值(value)

<select ng-init="selectedSite" ng-option="x for (x,y) in sites"></select>
<h1>你选择的值是:{{ selectedSite }}</h1>
<script>
    ...
        $scope.cars = {
            car01: {brand:"Ford", model:"Mustang", color:"red"},
            car01: {brand:"Fiat", model:"500", color:"white"},
            ...
        };
    ...
</script>

你选择的值为在 key-value对中的value

value在key-value对中也可是对象

在下拉菜单也可以不使用key-value对种的key,直接使用对象的属性。

<select ng-init="selectedCar" ng-option="y.brand for (x,y) in cars"></select>

 

10、AngularJS 表格

<table>
    <tr ng-repeat="x in names">
        <td>{{ $index+1 }}</td> <!-- 表格显示序列号 -->
        <td>{{ x.Name }}</td>
        <td>{{ x.Country}}</td>
    </tr>
</table>

<table>
    <tr ng-repeat="x in names">
        <td>{{ $index+1 }}</td> <!-- 表格显示序列号 -->
        <td ng-if="$odd" ...>{{ x.Name }}</td> <!-- 奇数行 -->
        <td ng-if="$even" ...>{{ x.Country}}</td> <!-- 偶数行 -->
    </tr>
</table>

 

11、AngularJS HTML DOM

为HTML DOM 元素的属性提供了绑定应用数据的指令

ng-disabled 直接绑定应用程序数据到HTML的disabled属性

<button ng-disabled="mySwitch">点我!</button>
<input type="checkbox" ng-model="mySwitch" />按钮
{{ mySwitch }}

ng-show="true" --> 显示

ng-show="false" --> 隐藏

ng-init="hour=13"

ng-show="hour>12" --> 可见

ng-hide

 

12、AngularJS 事件

ng-click="count = count+1" ...

 

13、AngularJS 模块

模块定义了一个应用程序,是应用程序中不同部分的容器,是应用控制器的容器。

控制器通常属于一个模块。

angular.module --> 创建模块

angular.controller --> 添加控制器

 

14、AngularJS 表单

输入控件的集合: input、select、button、textarea

数据绑定:

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

CheckBox(复选框):

<input type="checkbox" ng-model="myVar">
<h1 ng-show="myVar">my Header</h1>

单选框:

<form>
    <input type="radio" ng-model="myVar" value="dogs">Dogs
    <input type="radio" ng-model="myVar" value="tuts">Tuts
    <input type="radio" ng-model="myVar" value="cars">Cars
</form>
<div ng-switch="myVar">
    <div ng-switch-when="dogs">...</div>
    ...
</div>

下拉菜单:

<select ng-model="myVar">
    <option value="">
    <option value="dogs">Dogs
    <option value="tuts">Tuts
    <option value="cars">Cars
</select>

<script>
    ...
    $scope.user = angular.cope($scope.master);
    ...
</script>

 

15、AngularJS 输入验证

$dirty

$valid

$invalid

$pristine

 

16、AngularJS 包含

ng-include --> 可包含HTML内容、AngularJS代码

<div ng-include="'runoob.htm'">

跨域包含:ng-include不允许包含其他域名的文件,若需要包含其他域名的文件,需设置域名访问白名单。

<div ng-include="'http://c.runoob.com/runoobtest/...'">
<script>
    ...
    app.config(function($sceDelegateProvider){
        $sceDelegateProvider.resourceUrlWhitelist([
            'http://c.runoob.com/runoobtest/**'
        ]);
    });
</script>

 

17、AngularJS 动画

angular-animate.min.js

需在应用中使用ngAnimate,ng-app="ngAnimate" 或 angular.module('myApp',['ngAnimate']);

添加或移除class的指令:

    ng-show

    ng-hide

    ng-class

    ng-view

    ng-include

    ng-repeat

    ng-if

    ng-switch

 

18、AngularJS 依赖注入

value --> 简单的 JavaScript 对象,用于向控制器传递值

factory --> 一个函数用于返回值,在 service 和 controller 需要时创建

service

provider --> 创建一个 service.factory 等(配置阶段),提供了一个 factory方法 get(),用于返回value/service/factory。

constant --> 常量,用来在配置阶段传递数值。

app.value("defaultInput", 5); // 创建value对象'defaultInput"并传递数据
app.controller("...", function(..., defaultInput){ ... }); // 将"defaultInput"注入到控制器
// 创建 factory "MathService" 用于两数的乘积
app.factory('MathService', function(){
    var factory = {};
    factory.multiply = function(a, b){
        return a*b;
    };
    return factory ;
});
// 在 service 中注入factory "MathService"
app.service('CalcService', function(MathService){ ... });

例:

var app = angular.module('app', []);
//1.
app.controller('myCtrl', function($scope){
    $scope.msg = '你好';
});
// Services 自定义有四种模式 value constant factory services provider

//2.value:是可以改变值的
app.value('realname', '赵六');
app.controller('myCtrl', function($scope, realname){
    $scope.msg = '你好';
    $scope.realnameV= realname;
});

//3.constant:值不可改变
// value 和 constant可以做一些小的配置文件的时候引用
app.value('realname', '赵六');
app.value('realname', '王五');
app.constant('http', 'http://www.baidu.com/');
app.constant('http', 'http://sohu.com/');
app.controller('myCtrl', function($scope, realname, http){
    $scope.msg = '你好';
    $scope.realnameV = realname;
    $scope.httpV = http;
});

//4.factory:开发中使用的最多
app.value('realname', '赵六');
app.constant('http', 'http://www.baidu.com/');
app.factory('Data', function(){
    return {
        msg: '你好啊!',
        setMsg: function(){
            this.msg = '...';
        }
    };
});
app.controller('myCtrl', function($scope, realname, http, Data){
    $scope.msg = '你好';
    $scope.realnameV = realname;
    $scope.httpV = http;
    $scope.dataV= Data;
    Data.setMsg();
});

//5.services:方法与factory类似
app.value('realname', '赵六');
app.constant('http', 'http://www.baidu.com/');
app.factory('Data', function(){
    return {
        msg: '你好啊!',
        setMsg: function(){
            this.msg = '...';
        }
    };
});
app.service('User', function(){
    this.firstname = '...';
    this.lastname = '...';
    this.getName = function(){
        return this.firstname + this.lastname;
    };
});
app.controller('myCtrl', function($scope, realname, http, Data, User){
    $scope.msg = '你好';
    $scope.realnameV = realname;
    $scope.httpV = http;
    $scope.dataV= Data;
    Data.setMsg();
    $scope.uname = User.getName();
});

// 其实 factory 创建方式是 service 的复杂版,下面这一段代码与上面的 service 一个道理
app.factory('Data', function(){
    return new dd();
});
function dd(){
    this.firstname = '...';
    this.lastname = '...';
    this.getName = function(){
        return this.firstname + this.lastname;
    };
}

 

19、AngularJS 路由

AngularJS 路由就是通过 #+标记 区分不同的逻辑页面,并将不同的页面绑定到对应的控制器上。如:http://runoob.com/#/first

.html

<!-- ng-app="routingDemoApp" -->

<a href="#1">首页</a>
<a href="#/computers">电脑</a>
<a href="#/printers">打印机</a>
<a href="#/blabla">其他</a>

<div bg-view></div>

.js

var app = angular.module('routingDemoApp', ['ngRoute']);

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

//路由配置对象语法规则
$routeProvider.when(url, {
    template: String, //在 ng-view 插入简单内容
    templateUrl: String, //在 ng-view 插入HTML模板文件
    controller: String,function或array, // 在当前模板上执行的 controller 函数,生成新的 scope
    controllerAs: String, // 为 controller 制定别名
    redirectTo: String,function, // 重新定向地址
    resolve: object<key, function>, // 制定当前 controller 所依赖的其他模板
});

 

猜你喜欢

转载自blog.csdn.net/qq_29326717/article/details/79650634
今日推荐