AngularJS(216)

Angular

provider的关系 https://segmentfault.com/a/1190000003096933

基本指令

no-repeat是所有内置指令中优先级最高的。

ng-app 指定AngularJS脚步执行作用域
ng-model 绑定html元素到数据
ng-init 初始化数据
ng-if从dom删除元素
ng-switch 如同switch适用于多个例子,有ngSwitchCase ngSwitchDefault
ng-hide 从dom隐藏元素
ng-options 这个有点多,放下面单独列一项
ng-disabled 绑定数据到html的disabled属性
ng-show ng-hide
ng-bind 是指定数据,和差不多
ng-cloak 加载时防止代码未加载完而发生的闪烁
ng-model 是双向绑定, 在ng-repeatng-model必须和ng-change连用
ng-class 绑定css:

  1. ng-class=”name” css类绑定变量name
  2. ng-class=”{true: ‘active’, false: ‘inactive’}[isActive]” 变量isActive为true时绑定active,为false时绑定inactive
  3. ng-class=”{‘sty1’: active, ‘sty2’: inactive}” active为true增加sty1,inactive为true增加sty2
  4. ng-class=”[sty1, sty2]”

ng-include用于包含外部的html文件,包含的内容将作为知指定元素的子节点
<div ng-include="'myfile.html'"> 注意:它是一个双引号和一个单引号
element ng-include="'filename'" onload="" autoscroll=""
<ng-include src="finelname" onload="" autoscroll="">
onload 文件载入后执行的表达式
autoscroll 是否指定视图的可滚动

ng-repeat 它里面有几个属性可以直接放html使用:
$index 序列号
$first 第一个元素是它是true,其它false ($last同理)
$middle 是否在中间
$even $index的值是否是偶数
$odd $index的值是否是奇数

1
2
3
<div ng-app="" ng-init="qu=1;pr=5">
<input type="number" ng-model="qu"></>
</div>

angular.module(name,[requires],[configfn]) 一个参数是获取,一个以上是创建。

先用ng-app指定模块名,再用angular.module创建对应angular的模型。模型是当前元素拥有的作用域。
再用ng-controller指定控制名,再用模型名.controller创建对应angular的控制器。控制器是当前元素的控制器
最后用$scope来添加要控制的属性

每个模型有个$rootScope是根,是各个controller中scope的桥梁。

angular.extend

对象第一层拷贝,如果第一层有属性则引用属性,返回结果
angular.extend(a, b, c) //依次将c和b的第一层属性拷贝给a,如果有属性则引用拷贝过去,返回a

module

angular.module('phonecatApp', ['phoneList']); 这个表示phonecatApp是依赖phoneList的;可以引用里面的服务和组件等。
但是有个问题就是,在html它会被定义到后面的DOM元素覆盖。

错误认识

ng-repeatng-controller不能放到同一元素(这个纠结了好久),如果放都要用奇淫技巧。

过滤器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<p>{{lastName|lowercase}}</p>//小写转换
<p>{{lastName|uppercase}}</p>//大写转换
<p>{{lastName|currency}}</p> //数字格式化为货币格式
<li ng-repeat="x in names | orderBy:'country'" />//x是结构体有country属性。先按国家排序,再遍历 (angular-phonecat step-6就有个很好的例子,它按照选择来排序)
#### 自定义过滤
$scope.myfilter = function(item) {return bool}; //这个过滤必须返回bool类型,来表示此元素是否要被过滤掉。更注意的是它只能配合filter
<li ng-repeat="x in names | filter:myfilter" /> //自定义函数过滤
////////此外当想用此来传俩个参数时有个问题
1.4版本的只能如此
$scope.myfilter = function(a) {
return function(x) { return a==x;};//这里参数x很关键,返回的必须是`repeat`里面的循环变量,执行时才能访问到它,达到俩个数的效果
}
1.6版本是支持多个参数的
直接filter:myfilter(a, b);
///////
myApp.filter('replace', function() {
return function(input, n1, n2) { return datas;}//这个过滤中则必须返回整个的数据。更注意它只能用于指令时,必须返回多个才行。
});
Result: {{ yourinput | replace:3:'b' }}

服务

它封装了很多浏览器东西,来作为自己的内建服务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
app.service("customerserver", function() {
this.myFunc = function(x) {};
});
app.controller('customers', function($scope, $location, $http, $interval, customerserver) {
$location.absUrl();//当前页面的url
$http.get("").then(function());//请求数据
$interval(function(){}, 1000);//定时器
customerserver.myFunc(3);//自定义服务
});
//自定义过滤使用自定义服务,注意传入的服务那块的代码
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x;
}
});
app.filter('myFormat',['hexafy', '$location' ,function(hexafy,$location) {
return function(x) {
return $location.absUrl();
return hexafy.myFunc(x);
};
}]);
<h1>{{255|myFormat}}</h1>

表格

感觉里面的$odd等是内部的

1
2
3
4
5
6
7
8
9
10
11
12
<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>

自定义指令

必须先建个前缀代码自己的命名空间, 如:

1
myApp.directive('ddDrie', function ) => <div dd-drie...> //以大写字符为界,前缀必须是小写,命名必须只有一个大写字符。

一般属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'EA', //E标签指令 A属性指令(默认) M注释 Cclass指令
priority: 3,//优先级
terminal: true,//执行此指令是否停止其它指令
template: '<h2 class="head">{{title}}</h2>',//输出类型
replace: true,//是否替换,就上面的输出类型是否替换上html上的元素。否-html就包含
scope: true,//这个属性传入bool时。默认false,true时会从父作用域创建一个自己的作用域
controllerAs: 'ctrl',//这个属性牛逼了。下面的scope例子中,controller自定义的变量只能在template或其他用 ctrl.name 来访问
bindToController: true,//这个组件的属性都被绑定到controller上了而不是scope上面。可以视为继承到了父controller的同名的指定属性
scope: {
//这些属性要注意,头最好加上命名前缀
mytest1: '@', //解析普通字符,即传入数据当字符处理
mytest2: '=', //解析数据,传入数据当数据处理
mytest3: '&', //解析函数, 传入数据当函数
},
};
});
////////////////scope例子
<body ng-app="myApp">
<div ng-controller="mycc">
<div runoob-directive runoobst1="ww" runoobst2="name" runoobst3="show(3)"></div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('mycc',['$scope',function($scope){
$scope.name = 'xiecg';
$scope.show = function(vvv) {
return vvv;
};
}]);
app.directive("runoobDirective", function() {
return {
scope: {
runoobst1: '@',
runoobst2: '=',
runoobst3: '&'
},
controller : ['$scope',function($scope) {
$scope.name = 'this is a xiecg';//这个添属性,只能内部访问(想要访问只能用controllerAs属性)。不能当数据传入给runoobst2
$scope.hehe = "hehe";
}],
template : '<p>{{runoobst1}}</p> <p>{{runoobst2}}</p> <p>{{name}}</p> <p>{{runoobst3()}}</p>'
};
});

全局API

angular.isString();
angular.isNumber();

依赖注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 创建 value 对象 "defaultInput" 并传递数据
mainApp.value("defaultInput", 5);
// 将 "defaultInput" 注入到控制器
mainApp.controller('CalcController', function($scope, CalcService, defaultInput){}
mainApp.factory('MathService', function(...) { return {}; }
mainApp.service('CalcService', function(...) { this...=...; }
mainApp.constant("configParam", "constant value");
mainApp.config(function($provide) {
$provide.provider('Mprovider', function() {
this.$get = function() { return {};}
});
});

上面的注入,除了config有点特殊,其它都可以互相随意注入放置.

路由

router的url:https://github.com/angular-ui/ui-router/wiki/URL-routing

1
2
url: "/contacts/:contactId"
$stateParams.contactId = 42;

module.run

config执行后就run,然后才是后面的

run可以直接注入config和provided,和controller差不多

resource

它封装了http,使的webapi连续等。
/:resource_id.:format 遇见.它会默认跳过,如:/:resid/:fo.json

  • 第一个参数是url
  • 第二个是为参数设置默认值;
      1. url参数默认值,多余的会被添加到?后,即当做api参数 e.g.给定模板/path/:verb与参数{verb:’greet’,salutation:’Hello’},将得到URL/path/greet?salutation=Hello
      1. 参数以@为前缀,表示此属性的值,从调用第三个参数的结果对象中取对应的属性值。
  • 第三个参数; {action: {method, params, isArray, headers…..}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
var cards = CreditCard.query(function() {
//由于query是get数组,初始url是默认的
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
card.name = "J. Smith";
card.$save();
//上面返回结果了,直接用返回结果继续匹配
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});

$modal的用法

  1. 新版本的angular-ui-bootstrap, 是$uimodal$uimodalInstance
  2. 为了传递数据请多用resolve,scope属性会多建一个
  3. 注意下面代码中弹出类的三个参数传入

angular弹出窗口,使用:
templateUrl: 模态窗口地址, 相应html用id标志
template:用于显示html标签
scope:一个作用域为模态的内容使用(事实上,$modal会创建一个当前作用域的子作用域)默认为$rootScope
controller:为$modal指定的控制器,初始化$scope,该控制器可用$modalInstance注入
resolve:定义一个成员并将他传递给$modal指定的控制器,相当于routes的一个reslove属性,如果需要传递一个objec对象,需要使用angular.copy()
backdrop:控制背景,允许的值:true(默认),false(无背景),“static” - 背景是存在的,但点击模态窗口之外时,模态窗口不关闭
keyboard:当按下Esc时,模态对话框是否关闭,默认为ture
windowClass:指定一个class并被添加到模态窗口中
open方法返回一个实例,该实例具有如下属性:
close(result):关闭模态窗口并传递一个结果
dismiss(reason):撤销模态方法并传递一个原因
result:一个契约,当模态窗口被关闭或撤销时传递
opened:一个契约,当模态窗口打开并且加载完内容时传递的变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/ng-template" id="myModalContent.html" /> <!--这一段html对应templateUrl属性,注意-->
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items"><a
ng-click="selected.item = item">{{ item }}</a></li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
1
<button class="btn" ng-click="open()">Open me!</button>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl',
function ($scope,$modal, $modalInstance, items) {// 注意在这里的三个参数和 父类的resolve对应属性
$scope.items= items;//这里必须要赋值,才能被html访问
$scope.selected = {
item: items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl : 'myModalContent.html',
controller : ModalInstanceCtrl,
resolve : {
items : function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(result) {
console.log(result);
}, function(reason) {
console.log(reason);// 点击空白区域,总会输出backdrop
// click,点击取消,则会暑促cancel
$log.info('Modal dismissed at: ' + new Date());
});
};
};

resolve

ui-routermodal都用到它,我就仔细看了下。
路由弹出也好,窗口弹出也是。为了让界面显示前准备好数据而使用这个属性(网络数据获取等)
它会在之前被设定好,再注入到控制器中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
resolve:{
user:function() {
return {
name:"perter",
email:"826415551@qq.com",
age:"18"
}
}
}
app.controller('myController',function($scope,user){
$scope.name=user.name;
$scope.age=user.age;
$scope.email=user.email;
$scope.user=user;
});

animation

ng-options

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<select ng-model="selectedItem" ng-options="item.name for item in items"><!--从items选出item,把item.namee作为选项-->
<select ng-model="selectedItem" ng-options="item.age as item.name for item in items"><!--从items选出item,把item.namee作为选项;然后绑定的selectedItem值,绑定到item.age上面(比如selectedItem = 2,它会自动替换到age为2的item的name上去)-->
<select ng-model="selectedItem" ng-options="item.name group by item.age for item in items"><!--ng对选择多个分组属性。从items选出item,把item.age作为分组标准,把item.namee作为选项-->
<select ng-model="selectedItem" ng-options="color.name group by color.type disable when color.disabled for color in colors"><!--同上,只是多了个禁用判断-->
$scope.countries = {
CN: '中国China',
US: '美国United States',
UK: '英国United Kingdom',
GR: '德国Germany'
};
<select ng-model="selectedItem" ng-options="k as v for (k, v) in countries"><!--这个允许对象来选择。(k,v)表示这是个k-v类型,k做绑定 v做显示-->
<select ng-model="selectedItem" ng-options="k as v for (k, v) in countries"><!---->
<select ng-model="selectedItem" ng-options="k as v for (k, v) in countries"><!---->

track by

单独放一项是因为它和ngoptions/ngrepeat都相关。
但是我认为如果有个id我ngoptions何必用这个再去筛选,就没看。
主要说下ngrepeat

    1. <div ng-repeat="link in links" ></div>当links=[“1”, “1”, “4”,”4”]时angular会报错,不允许重复
      这时要么给这些加个属性id用来标志,”link in links track by link.id”
      要么懒惰的用 “link in links track by $index”
    1. 还是上面的例子,当links发生变化时。必然会让删除已有dom,再重新添加新的。1.2添加的新机制会修改已有的不会重新创建。但是这个就只能用第一种方法了,不能再$index偷懒了。

查找dom

jqLite太难用了,返回的还是它的对象。算了。

用这个,正好还可以找到属性对应的dom

1
2
3
4
var dd = angular.element(document.querySelector('ul'));
var dd = angular.element(document.querySelector('[id="ew"]'));//id="ew"的dom
//我才发现既然angular.element支持 css的选择器,那就可以用 `.modal-body input`这种css语法来选择呀。。。。。。晕!!太笨了。。

this和$scope

今天想起对比下这俩个:

  • $scope

    1
    2
    3
    function dd($scope) { $scope.test = "dd"; }
    <div ng-controller="dd"> {{test}} </div>
  • this

    1
    2
    3
    function dd() { var vm = this; this.test = "dd" ;}
    <div ng-controller="dd as vm"> {{vm.test}}</div>

使用起来一个麻烦js文件,一个麻烦html文件,但效果无异。

但是区别在于
$scope可以访问到父类的$scope的属性和成员;但是当具有相同属性或成员时,$scope就拥有自己的空间,并不会覆盖。

angular思想
Angular分俩个块儿:配置块和运行块(它更多的在于思想)

配置块
angular.config 这个会在配置块执行,然而上面的依赖注入只有provider才能在配置块被执行。
所以设计provider为初始化设置,$get返回一个对象,让所有注入

factory要返回一个对象,所以一般被设为仅仅需要的是一个方法和数据的集合且不需要处理复杂的逻辑的时候
service当使用在功能控制比较多的service里面


provide.decorator

这个功能用于向已有的服务里面添加新的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Mail = function() {
this.receiver = '';
this.body = '';
this.cc = [];
};
Mail.prototype.setReceiver = function(receiver) {
this.receiver = receiver;
};
Mail.prototype.setBody = function(body) {
this.body = body;
};
angular.module('A', []).service('Mail', Mail);
1
2
3
4
5
6
7
8
9
10
11
12
angular.module('B', ['A']).config(function($provide) {
$provide.decorator('Mail', function($delegate) {
$delegate.addCC = function(cc) {
this.cc.push(cc);
};
return $delegate;
});
})
.controller('TestCtrl', function($scope, Mail) {
Mail.addCC('jack');//这些mail服务就多了个调用函数
console.log(Mail);
});

provider笔记

初始化必须

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
angular.module()
.provider('linkAll', function() {
var l1 = '';
var l2 = '';
this.SetLinkTitle = function(v) {
l1 = v;
}
this.SetLinkUrl = function(v) {
l2 = v;
}
this.$get = function() {
return {
linkTitle: l1,
linkUrl: l2,
}
}
});

1
2
3
4
5
6
//在config对它访问和在控件对它访问是完全不一样的
config (['linkAllProvider', function(linkAllProvider){
linkAllProvider.SetLinkTitle(3);
}]);
controller(['linkAll', function(linkAll) {linkAll.linkTitle;}])

ocLazyLoad

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ocLazyLoadProvider.config({
debug: true, //官方说这是为了oclazy向控制台输出信息
serie: true, //当modules的多个模块文件全都互相依赖时,为了全部加载而在全局使用
modules: [{
name: 'kzts.modules.products.search',
files: [
'/ts/modules/products/search/search.module.js',
'/ts/modules/products/search/products-search.js',
'/ts/modules/products/search/products-search-modal-controller.js'
],
serie: true //指定核心模块,当多个模块加载时,保证核心模块先被加载
},
{
... //这些格式如上
} ]
});
//.....
resolve: {
loadModule: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load('errorView');
}]
}

UI-Router

跳转方式
$state.go()
ng-href: 会ng-href="/av/"
ui-sref: 这个需要url那边配合 https://github.com/angular-ui/ui-router/wiki/URL-Routing#url-parameters

1
2
3
4
5
6
7
url: '/users/:id/details/{type}/{repeat:[0-9]+}?from&to'
// Then you navigated your browser to:
'/users/123/details//0'
// Your $stateParams object would be
{ id:'123', type:'', repeat:'0' }

href

  • 父子路由

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    .state('blog', ...)
    .state('blog.index', ...);
    //通过名称中的一个`.` 来区分父子路由
    .state('list', {
    parent: 'contacts', //指定父路由
    })
    //子路由会继承父路由的依赖注入项
    resolve: {rea:...}
    resolve: {reb:...}
    conttroller: function(rea, reb) {...}
    //子路由会继承父路由的data属性,并可以重写
    $stateProvider.state('parent', {
    data: {...}
    })
    function Ctrl($state){
    console.log($state.current.data.customData1) // outputs 5;
    console.log($state.current.data.customData2) // outputs "blue";
    }
  • abstract
    官方说这个是为了方便定义虚拟的父,有段url是为所有子节点准备。
    里面必须有ui-view

https://github.com/angular-ui/ui-router/wiki/Nested-States-&-Nested-Views

  • views
    当一个html出现多个ui-view时使用
    1
    2
    3
    4
    5
    <body>
    <div ui-view="filters"></div>
    <div ui-view="tabledata"></div>
    <div ui-view="graph"></div>
    </body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$stateProvider
.state('report',{
views: {
'filters': {
templateUrl: 'report-filters.html',
controller: function($scope){ ... controller stuff just for filters view ... }
},
'tabledata': {
templateUrl: 'report-table.html',
controller: function($scope){ ... controller stuff just for tabledata view ... }
},
'graph': {
templateUrl: 'report-graph.html',
controller: function($scope){ ... controller stuff just for graph view ... }
}
}
})

多视图的命名允许使用相对和绝对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- index.html (root unnamed template) -->
<body ng-app>
<div ui-view></div> <!-- contacts.html plugs in here -->
<div ui-view="status"></div>
</body>
<!-- contacts.html -->
<h1>My Contacts</h1>
<div ui-view></div>
<div ui-view="detail"></div>
<!-- contacts.detail.html -->
<h1>Contacts Details</h1>
<div ui-view="info"></div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
$stateProvider
.state('contacts', {
// 根状态,对应的父模板则是index.html
// 所以 contacts.html 将被加载到 index.html 中未命名的 ui-view 中
templateUrl: 'contacts.html'
data: {custom: 5}
})
.state('contacts.detail', {
views: {
// 嵌套状态,对应的父模板是 contacts.html
// 相对命名
// contacts.html 中 <div ui-view='detail'/> 将对应下面
"detail" : { },
// 相对命名
// 对应 contacts.html 中的未命名 ui-view <div ui-view/>
"" : { },
// 绝对命名
// 对应 contacts.detail.html 中 <div ui-view='info'/>
"info@contacts.detail" : { }
// 绝对命名
// 对应 contacts.html 中 <div ui-view='detail'/>
"detail@contacts" : { }
// 绝对命名
// 对应 contacts.html 中的未命名 ui-view <div ui-view/>
"@contacts" : { }
// 绝对命名
// 对应 index.html 中 <div ui-view='status'/>
"status@" : { }
// 绝对命名
// 对应 index.html 中 <div ui-view/>
"@" : { }
});
function($state) {
$state.current.data.custom;
}
  • $urlRouterProvider
1
2
$urlRouterProvider.when('', '/index');// 把空路由重定向到 /index
$urlRouterProvider.otherwise('/index');//重定向无效路由

最后给个api查询 ##: https://github.com/angular-ui/ui-router/wiki/Quick-Reference

多个视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--main.html-->
<head>
<title></title>
<script src="./angular.js"></script>
<script src="./angular-ui-router.js"></script>
<script src="./App2.js"></script>
</head>
<body data-ng-app="myApp">
<h1>多ui-view</h1>
<div ui-view></div>
<div ui-view="chart"></div>
<div ui-view="data"></div>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/home");
$stateProvider.state("home", {
url: "/home",
views: {
"": {
template: "<h1>HELLO!</h1>"
},
"chart": {
template: "chart"
},
"data": {
template: "data"
}
}
})
.state("index", {
url: "/index",
views: {
"": {
template: "<h1>HELLO!</h1>"
},
"data": {
template: "data-index"
}
}
})
});

多层视图

1
2
3
4
5
6
7
8
9
10
11
12
<!--main.html-->
<head>
<title></title>
<script src="./angular.js"></script>
<script src="./angular-ui-router.js"></script>
<script src="./App.js"></script>
</head>
<body data-ng-app="myApp">
<h1>AngularJS Home Page (Ui-router Demonstration)</h1>
<div ui-view></div>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// App.js
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/PageTab");
$stateProvider
.state("PageTab", { //这个有个缺点,就是没有默认指定view的显示页。有俩种方法
url: "/PageTab", //1、 在PageTab里面加$state.transitionTo('PageTab.Page1');来显示指定显示页
templateUrl: "PageTab.html"//2. 使用abstract,向父view添加abstract=true属性。但是要设置跳转页面when('', '/PageTab/Page1'),因为直接跳转到父页面是无法显示的。
})
.state("PageTab.Page1", {
url:"/Page1",
templateUrl: "Page1.html"
})
.state("PageTab.Page2", {
url:"/Page2",
templateUrl: "Page2.html"
})
.state("PageTab.Page3", {
url:"/Page3",
templateUrl: "Page3.html"
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!-- PageTab.html -->
<div>
<div>
<span style="width:100px" ui-sref=".Page1"><a href="">Page-1</a></span>
<span style="width:100px" ui-sref=".Page2"><a href="">Page-2</a></span>
<span style="width:100px" ui-sref=".Page3"><a href="">Page-3</a></span>
</div>
<div>
<div ui-view/>
</div>
</div>
<!-- Page1.html -->
<div>
<div>
<h1>Page 1 content goes here...</h1>
</div>
</div>
<!-- Page2.html -->
<div>
<div>
<h1>Page 2 content goes here...</h1>
</div>
</div>
<!-- Page3.html -->
<div>
<div>
<h1>Page 3 content goes here...</h1>
</div>
</div>

translate

可以作过滤使用
可以作属性使用
还可以指定参数:

1
2
3
VARBLE: 'HI, {name}' //字典
<p translate="VARBLE" translate-values="{name:'wq'}" />// HI, wq

translations注册
preferredLanguage选择默认语言。 等同use
fallbackLanguage 动态切换语言时,先fall再use就好了。

useLocalStorage 为了方便快速切换,提供storage来。localstorage依赖cookiestorage。

useStaticFilesLoader 使用静态文件

1
2
3
4
5
6
7
8
9
10
$translateProvider.useStaticFilesLoader({
files: [{
prefix: '/locale/',
suffix: 'tt.json'
}, {
prefix: '/absolute/path/to/locale-', //locale-en locale-cn
suffix: '.json'
}
});
$translateProvider.preferredLanguage('en');

// //