angularjs学习笔记02 - make it easy      

Zhenyi's blog

angularjs学习笔记02

    

1.css和样式

一般页面中会用到动态的css,使用可以完成,比如我们有样式

.menu-active{}
.menu-disabled{}

那么模版就可以这么写:

<html>
	…
	<div class="menu-"></div>
	…		
</html>

然后在controller里面修改status的值就可以了。

但是这样有一个隐患,这样的css类一定要有某种格式来写,在复杂的项目中可能会变的不可维护,于是Angular提供了另一种解决方案。那就是使用ng-class

看下面的代码

...
<style>
    .error{color: red}
    .warning{color: yellow}
</style>
…
<div ng-controller = "textController" >
    <p ng-bind="message.someText" ng-class='{error: style.isErr, warning: style.isWarn}'></p>
    <button ng-click="setColor(0);">red</button>
    <button ng-click="setColor(1);">yellow</button>
</div>
…
<script>
var myAppModule = angular.module('myApp', []);

myAppModule.controller('textController',function($scope) {
    $scope.message = {someText:"Here is the text"};

    $scope.style = {
        isErr: false,
        isWarn: true
    }

    $scope.setColor = function(para){
        $scope.style.isErr = !!!para;
        $scope.style.isWarn = !!para;
    }
});
</script>
…

ng-class里面可以直接写表达式{error: style.isErr, warning: style.isWarn},当属性style.isErr为true时就会添加css类为error的类,false则去掉该类。

表达式可以写的更加复杂一些,里面可以添加各种表达式,这样就可以做很多事情了。

2.filter

filter也是Angular里面特别好用的一个功能,顾名思义,就是过滤器,使用格式是:

Augular已经内置了不少的过滤器,比如uppercase,currency等等,例如

dddd

得到的结果会是

DDDD

当然内置的肯定是不够用的,那么我们可以自己定义filter,比如我只要首字母大写

var myAppModule = angular.module('myApp', []);

myAppModule.filter('firstUpper',function(){
   var filter = function(input){
       if(!input) return '';
       input = input.charAt(0).toUpperCase() + input.slice(1);
       return input;
   }
    return filter;
});

使用的时候只要

dddd

得到的结果会是

Dddd

3.$watch

监控所有数据模型变化,先在这里挖个坑,以后再填(会填么?)

4.使用Module组织依赖关系

为了维护大型的应用,现在很多项目都是使用模块化管理代码的,包括我现在在用的seajs。Angular里面也有模块化的功能,提供了三种不同的方法,这里只说一种,那就是factory。直接上代码:

myAppModule.factory('Items',function(){
    var items = {};
    items.query = function(){
        //一系列逻辑代码
        return [
            {name: 'name1',type: 'type1'},
            {name: 'name2',type: 'type2'},
            {name: 'name3',type: 'type3'}
        ]
    }
    return items;
});

这里新建了一个Items的服务,里面返回一个对象,这个服务可以由controller直接使用,比如

myAppModule.controller('tableController',function($scope,Items) {
    $scope.restaurants = Items.query();        
});

html代码:

 <table ng-controller = "tableController">
    <tr ng-repeat = 'res in restaurants' >
        <td></td>
        <td></td>
    </tr>
</table>

可以得到一个三行的表格。

一般服务的命名规则不要使用$开头,免得和内置的对象命名冲突。

2014.04.22 施桢屹