AngularJs详细

正经的来啦

(MVC)

  • View(视图), 即 HTML。
  • Model(模型), 当前视图中可用的数据。
  • Controller(控制器), 即 JavaScript 函数,可以添加或修改属性。
    修改了视图,模型和控制器也会相应更新。
<div ng-app="myApp" ng-controller="myCtrl">

<input ng-model="name">

<h1>我的名字是 {{name}}</h1>/*视图*/

</div>

<script>
var app = angular.module('myApp', []);/*模型*/
/*控制器*/
app.controller('myCtrl', function($scope) {
    $scope.name = "John Dow";
});
</script>

AngularJS指令

ng-model

使用ng-model进行双向数据绑定:就是将ng-model=“value”设置在输入框中,实现与AngularJS的表达式{{变量名}}的数据绑定。ng-model的value值就是AngularJS表达式中的变量名。


数量: <input type="number"	ng-model="quantity">
价格: <input type="number" ng-model="price">

<p><b>总价:</b> {{ quantity * price }}</p>
ng-repeat

ng-repeat就是重复html元素
通常用来循环数组
<li ng-repeat="x in names"> {{ x }} </li>
names是一个数组,输出数组中的每个值,每个值对应一个li标签。
通常用在数组对象上。

names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]
<li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>

ng-init 指令为 AngularJS 应用程序定义了 初始值。
ng-app 指令定义了 AngularJS 应用程序的 根元素,就是AngularJS的作用范围。


Scope作用域

Scope的使用

scope是一个JavaScript对象,带有属性和方法。应用于变量和函数。

<div ng-app="myApp" ng-controller="personCtrl">

名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
<br>
姓名: {{fullName()}}

</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    }
});
</script>

在构造控制器的时候,可以将$scope对象当做控制器函数的参数使用。

app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";
});

在视图(html)中获取$scope对象的参数的时候,可以直接添加属性名,不需要添加$scope前缀,如:{{carname}} 。

$rootScope 与$scope的作用域范围。

app.controller('myCtrl', function($scope, $rootScope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    $rootScope.lastname = "Refsnes";

$scope作用在myCtrl这个控制器controller的范围内
$rootScope作用在ng-app控制的范围内,可以在各个controller中使用。


AngularJS过滤器

过滤器可以通过一个管道字符(|)和一个过滤器(currency,filter,lowercase,uppercase,orderBy)添加到表达式中。
用法:

<p>姓名为 {{ lastName | uppercase }}</p>
<p>姓名为 {{ lastName | lowercase }}</p>
<p>总价 = {{ (quantity * price) | currency }}</p>
/*排列数组*/
<li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ', ' + x.country }}
</li>
/*过滤器绑定输入:过滤器通过管道字符"|"与过滤器添加导致令中,然后过滤器之后跟一个冒号和一个模型的名字name(ng-model="name")*/
<li ng-repeat="x in names | filter:test | oderBy:'country'">
    {{x.name | uppercase}}+{{x.country}}
</li>

AngularJS服务(service)

AngularJS服务是一个函数或者一个对象

$location服务

有一个$location服务可以返回当前页面的url地址。

var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope,$location){
    $scope.myUrl = $location.absUrl();
});

$http服务

AngularJS中的常用的服务,用来向服务器发送请求,响应服务器传过来的数据。
例如,使用$http向服务器请求数据:

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

AngularJS $http 是一个用于读取web服务器上数据的服务。
$http.get(url) 是用于读取服务器数据的函数。
请求读取PHP数据,例子:

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.runoob.com/try/angularjs/data/Customers_JSON.php")
    .success(function(response) {$scope.names = response.records;});
});
</script>

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

2秒之后,myHeader的内容被替换为“How are you today ?”


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

显示以1秒变化的时钟。


AngularJS Select(选择框)

ng-options创建下拉列表

ng-options指令选择的是一个对象
例如:
数据源对象:使用对象作为数据源, x 为键(key), y 为值(value):

$scope.cars={
car01:{brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
};

使用ng-options,选择的为key-value键值对里面的value值,是通过键key来选择,也可以将value看做一个对象。


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

<h1>你选择的是: {{selectedCar.brand}}</h1>
<h2>模型: {{selectedCar.model}}</h2>
<h3>颜色: {{selectedCar.color}}</h3>

下拉列表中有car01 car02 car03.想,选择car01 会出现相应的值的信息。

ng-repeat与ng-options的区别

数据源对象:

$scope.sites = [
    {site : "Google", url : "http://www.google.com"},
    {site : "Runoob", url : "http://www.runoob.com"},
    {site : "Taobao", url : "http://www.taobao.com"}
];

ng-repeat有局限性,它的选择的值是一个字符串;

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

<h1>你选择的是: {{selectedSite}}</h1>

使用 ng-options 指令,选择的值是一个对象:

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

<h1>你选择的是: {{selectedSite.site}}</h1>
<p>网址为: {{selectedSite.url}}</p>

两者同样会出现,点击下拉列表中的Google出现其url。


AngularJS模块module

模块介绍:

模块是应用程序中不同部分的容器,常用作控制器的容器。
通常app.js中放置整个项目中使用的各个模块,将控制器放在控制器的js文件中。
模块中使用控制器的例子:

var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
    $scope.firstname="Bi";
    $scope.lastname="Sha";
});

定义模块:
var app=angular.module("myApp",[]);

其中,第一个参数"myApp"是模块的名字,应用在html的作用范围中ng-app="myApp";
第二个参数[]定义模块的依赖关系,如果有依赖,就将依赖的模块名写在"[]"内部。


AngularJS 路由

基本介绍

路由就是通过不同的url来访问不同的内容,通过AngularJS可以实现多视图的单页weby应用。
通常我们的url格式为http://XX.com/first/page,在AngularJS当中,单页的web应用通过#+标记。如:http://XX.com/#/first。
解释:当点击http://xx.com/#/page的时候,向服务器请求的地址都是http://xx.com/,#之后的内容会在向服务器发送请求的时候会被客户端忽略掉,所以需要在客户端实现#号后面的内容功能。


AngularJS 路由的用法
<html>
    <head>
    	<meta charset="utf-8">
        <title>AngularJS 路由实例</title>
    </head>
    <body ng-app='routingDemoApp'>
     
        <h2>AngularJS 路由应用</h2>
        <ul>
            <li><a href="#/">首页</a></li>
            <li><a href="#/computers">电脑</a></li>
            <li><a href="#/printers">打印机</a></li>
            <li><a href="#/blabla">其他</a></li>
        </ul>
         
        <div ng-view></div>
        <script src="angular.min.js"></script>
        <script src="angular-route.js"></script>
        <script>
            angular.module('routingDemoApp',['ngRoute'])
            .config(['$routeProvider', function($routeProvider){
                $routeProvider
                .when('/',{template:'这是首页页面'})
                .when('/computers',{template:'这是电脑分类页面'})
                .when('/printers',{template:'这是打印机页面'})
                .otherwise({redirectTo:'/'});
            }]);
        </script>
     
     
    </body>
</html>
实例代码分析

1、要载入angular-route.js
2、注入ngRoute作为主模块的依赖模块
3、使用ng-view指令规定显示视图页面的位置。
4.配置$routeProvider,用$routeProvider来定义路由规则。

module.config(['$routeProvider',function($routeProvider){
    $routeProvider
    .when('/',{template:'首页'})
    .when('/computers',{template:'电脑分类页'})
    .when('/printers',{template:'打印机页'})
    .otherwise({redirectTo:'/'});//返回首页。
}]);

使用config函数来配置路由规则:

  • 通过使用configAPI,把$routeProvider注入到配置函数,并使用$routeProvide.whenAPI来定义路由规则。
  • $routeProvider使用when(path,object)&otherwise(path,object)函数来按顺序定义所有路由。两个参数:
    + path:URL或者URL正则规则
    + object: 路由配置的对象:
    配置路由对象语法:
$routeProvider.when(url, {
    template: string,
    templateUrl: string,
    controller: string, function 或 array,
    controllerAs: string,
    redirectTo: string, function,
    resolve: object<key, function>
 });
        template:在 ng-view 中插入简单的 HTML 内容
        templateUrl:在 ng-view 中插入 HTML 模板文件
$routeProvider.when('/computers', {
       templateUrl: 'views/computers.html',
 });
        controller:function、string或数组类型,在当前模板上执行的controller函数,生成新的scope。
        controllerAs:string类型,为controller指定别名。
        redirectTo:重定向的地址。
        resolve:指定当前controller所依赖的其他模块。
原文地址:https://www.cnblogs.com/this-xiaoming/p/5807799.html