码迷,mamicode.com
首页 > Web开发 > 详细

AngularJS入门

时间:2017-08-20 20:02:30      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:概念   tor   优先级   direct   rod   min   名称   常见   数据   

AngularJS是一个前端JavaScript框架,背后有Google支持。这个框架最早是09年发布的,随后发展迅速,尤其是最近,流行度很高。和其他框架不同,AngularJS有很多独特的特性,使得其非常与众不同。考虑到本人的文章多写的逻辑混乱,如果你对AngularJS不了解,推荐你先去其[官网](http://www.angularjs.org)看看。对于我来说,最吸引我的两个特性是双向绑定以及依赖注入。前者免去了开发时显示的刷新DOM,能让开发者更专注在逻辑上,而后者则使得测试以及集成变得非常方便。

### Hello,World ###
先来看一个经典的Hello World。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
<script>
function HelloController($scope) {
    $scope.person = {
    name: "World"
}
 
$scope.sayHelloWorld = function() {
    alert($scope.person.name);
}
</script>
</head>
<body ng-app>
<div ng-controller="HelloController">
    <input type="text" ng-model="person.name" />
    <button ng-click="sayHelloWorld()"></button>
</div>
</body>
</html>

  

### Controller ###
在Angular中,Controller主要负责初始化scope,包括数据以及所需要的函数。上面的HelloController就是个典型的Controller,另外一种更加强大的定义方式允许你声明所依赖的模块。

1
2
3
4
5
6
7
8
9
10
var controllers = angular.module(‘demo.controllers‘);
controllers.controller("demoController", [‘$scope‘‘$http‘function($scope, $http) {
    $scope.test_data = {
        value: ‘test data‘
    };
 
    $scope.test_function = function() {
        alert("test function");
    };
}]);

  

Controller比较直观,需要注意的有两个地方,一是使用$watch关注某个表达式的值,当发生变化时做相应操作,二是使用外部库操作数据,需要使用apply通知angular,不然的话很有可能外部库更新了数据,但angular却没有做相应更新。

### Directive ###
在前端开发中,经常需要操作DOM,而且有时候需要使用一大堆HTML来构建一个常用的组件,例如Google+信息流中的一条信息,在Angular中这都属于Directive的作用,这也就意味着在Controller中操作DOM是个错误的做法。

通常情况下,Directive定义时采用CamelCase规则进行命名,而在使用时则使用横线进行分隔。

Directive的定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var directives = angular.module(‘demo.directives‘, []);
 
directives.directive(‘customDirective‘function() {
return {
     restrict: ‘ECMA‘,
     template: ‘<nav></nav>‘,
     templateUrl: ‘directive.html‘,
     replace: false,
     priority: 0,
    transclude: false,
    scope: false,
    terminal: false,
     require: false,
    controller: function(scope, element, attrs, transclude, otherInjectables {},
    compile: function(element, attrs, transclude) {
        return {
            pre: function preLink(scope, element, attrs, controller) {},
            post: function postLink(scope, element, attrs, controller) {}
       };
    },
    link: function(scope, element, attrs) {
    }
};
});

  

restrict: 指定了directive的使用形式,共有四种:
1. Element(restrict定义时的E)
2. Attribute(restrict定义时的A)
3. Class(restrict定义时的C)
4. Comment(restrict定义时的M)

compile:在directive中如果需要对DOM元素进行处理,基本都是在这个函数中进行。仔细看这个函数,compile并不能访问scope,
link:此函数的主要作用就是对DOM和scope做数据绑定。和compile不同,在这个函数中,已经可以访问scope了。
template和templateUrl:用于指定directive对应的模板,前者直接使用字符串定义模板,而后者则通过url链接外部模板文件。在模板中可以使用对应controller或者rootScope中的scope,当然也有例外,具体请看关于scope的解释。
replace:指定是否使用模板替换directive作用的DOM元素。
priority:指定优先级,angular在处理directive时,会将页面出现的所有directive按优先级排序,一般这个数值都是不指定的。
controller:directive对应的controller,通常用于directive之间的通信。在这个函数中,所有绑定到this上的变量,其他的directive都能通过使用require来进行访问。
require:通过指定某个directive的名字,来访问其对应的controller。其中以?作为前缀时,如果找不到此directive将报错,而以^为前缀,将会在父元素进行递归查找,可以使用数组来引入多个directive,如[‘directive1‘,‘directive2‘,‘directive3‘]
scope:用于指定当前directive所对应的scope,不同的取值之间的影响非常大。

1. false:此时directive与父元素共享scope
2. true:此时directive有自己的scope,该scope继承父元素所对应的scope
3. isolate:directive有自己的scope,该scope不会继承自父元素对应的scope,但是仍然可以通过scope.$parent访问父节点的scope。这不是一个推荐的做法,因为这样就对父元素进行了限制,影响了directive的使用范围。如果想在父子元素之间共享数据,可以明确指定那些元素需要父子之间共享。方法共有三种:
使用@将父级scope中的属性绑定到本地scope中,单向绑定,这个值总是字符串,在template中需要使用{{}}
使用=同上,只不过这里是双向绑定,在template中可以直接给出父级scope的属性名称
使用&用于倒入函数或者表达式

transclude:用于控制是否要将该directive的子元素添加到模板中ng-tranclude指定的元素之下

### Service ###
在Angular中,Service是一些提供常见功能的单例对象。诸如上面出现$http等,其使用也是比较简单的,只要在使用时声明这个依赖就可以了,例如上面的demoController。其定义方式主要有一下几种:
1. service只是简单的数值可以使用constant(name,value)进行注册,如果时已经存在的对象,可以使用value(name,value)进行注册

1
2
3
4
5
6
7
8
9
10
11
var services = angular.moudle(‘demo.services‘, []);
services.constant(‘number‘, 42);
services.constant(‘string‘‘string‘);
 
var existingService = {
    notify: function(msg) {
        alert(msg);
    }
};
 
services.value(‘notify‘, existingService);

  

2. 注册一个service构造函数

1
2
3
4
services.service(‘demoService2‘function() {
    this.func = function() {
    };
});

  

3. 注册一个工厂函数用于创建service实例,这种方式可以在创建服务实例之前做些处理

1
2
3
4
5
6
7
services.factory(‘demoService1‘function(msg) {
    // some processing code
    return {
        func: function() {
        }
    };
});

  

4. 使用provider,使用这种方式,复杂一点,但是好处是可以对service进行配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
services.provider(‘demoService3‘function() {
    this.value = "string";
    this.$get = function() {
       var value = this.value;
        return {
            print: function() {
                console.log(value);
            }
        }
    }
 
    this.setValue = function(value) {
        this.value = value;
    }
});

  

// 使用config可以对provider进行配置

1
2
3
services.config(function(demoService3Provider) {
    demoServiceProder.setValue(‘hello‘);
});

  

当然,创建服务也是可以声明依赖的,具体格式和controller类似,不再罗嗦。

Angular还所有很多概念,包括router和filter等,我很少用到,没有细研究过。

AngularJS入门

标签:概念   tor   优先级   direct   rod   min   名称   常见   数据   

原文地址:http://www.cnblogs.com/bzzhzblog/p/7400936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!