Angularjs基础教程

Angularjs-基础教程

一些angualr的基础概念,适合入门。

1.下载

推荐 bower 或 npm 安装。

bower install angular
bower install angular-route

2.简单介绍使用

1.ng-app

决定了angularjs的作用域范围,你可以如下使用

//让angularjs渲染整个页面

...

//让angular只作用于某div,渲染页面的一部分


...

2.ng-model

模型和视图的双向数据绑定. ng-model 称为指令 {{test}} 插值表达式,实际上也是一个指令

譬如<input type="text" ng-model='test' /> <p>{{test}}</p> ,当你在文本框输入时,数据模型被改变,{{test}}的值跟着改变。

<!doctype html>






{{test}}



3.angular.module

语法:angular.module(moduleName, [requires], [configFn]); 用于创建、获取模块。

var app = angular.module(name, [requires], [configFn]);
//name 创建或获取的模块名
//requires 依赖的模块数组,['ngRoute','ngAnim',..]
//configFn 配置函数,同module.config

4.controller

控制器和作用域对象是一一对应的,控制器内定义为作用域初始化数据和方法

mycontroller = mymodule.controller('name', Constructor); //传入控制器名 和 控制器构造函数

<!doctype html>






{{test}}

5.value

value方法是定义服务的方式之一,类似 constant,factory,service

//name是service的名称,object是值,
mymodule.value(name, object); // 其实就是配置模块内的变量和它的值

<!doctype html>





{{test}}


5.factory

语法 mymodule.factory(serciceName, providerFn); 调用工厂函数providerFn,返回的对象即为对应的服务。

<!doctype html>






{{test}}


{{output}}

6.provider

语法: mymodule.provider(serviceName, providerFn); 实际上通过 new providerFn().$get(),来获得对应的服务, 跟 service方式定义服务的原理比较类似。

<!doctype html>






{{test}}


{{output}}

7.service

语法: mymodule.service(serviceName, constructor); , 实际上通过 new constructor() 来获得对应的服务。

var app = angular.module('myapp',[])
.value('testvalue','sindy')
.service('testservice',
function(testvalue){
this.lable = function(){
return "this will output:hello "+testvalue;
}
}
);
app.controller('mytest',function($scope,testvalue,testservice){
$scope.test = "hello "+ testvalue;
$scope.output = testservice.lable();
});

8.constant

语法:mymodule.constant(serviceName, object); 模块内定义常量

var app = angular.module('myapp',[])
.value('user','sindy')
.constant('country','china')
.service('greetSvc',
function(user, country){
this.hello = function(){
return "hello everyone, I am " + user + ", come from " + country;
};
}
);
app.controller('myctrl',function($scope,user,greetSvc){
$scope.test = "hello "+ user;
$scope.output = greetSvc.hello();
});




angular定义服务的方式




双向数据绑定


{{test}}



mymodule.value


myname is:{{username}}




mymodule.factory


{{username}}





mymodule.provider


{{username}}





mymodule.service


{{username}}





mymodule.constant


{{username}} {{howold}}




posted @ 2016-04-07 13:55  stephenykk  阅读(337)  评论(0)    收藏  举报