学习笔记之AngularJS(一)

一、一个简单的示例

test.html

<!DOCTYPE html>
<!--将AngularJS应用到HTML文件-->
<html ng-app="todoApp">
<head>
    <title>TO DO List</title>
    <link href="../bootstrap.css" rel="stylesheet"/>
    <link href="../bootstrap-theme.css" rel="stylesheet"/>
    <script src="../angular.js"></script>
    <script>
        // 创建一个数据模型
        var model = {
            user: "Adam",
            /*            items: [{action: "Buy Flowers", done: false},
                            {action: "Get Shoes", done: false},
                            {action: "Collect Tickets", done: true},
                            {action: "Call Joe", done: false}]*/
        };

        // AngularJS应用由一个或多个模块组成。模块是由调用angular.module方法而创建的,如下:
        var todoApp = angular.module("todoApp", []);

        // 创建一个控制器
        todoApp.controller("ToDoCtrl", function ($scope) {
            $scope.todo = model;
            // 创建控制器行为
            $scope.incompleteCount = function () {
                var count = 0;
                angular.forEach($scope.todo.items, function (item) {
                    if (!item.done) {
                        count++
                    }
                });
                return count;
            }
            // 创建依赖于其他行为的行为
            $scope.warningLevel = function () {
                return $scope.incompleteCount() < 3 ? "label-success" : "label-warning";
            }
            // 响应用户输入
            $scope.addNewItem = function (actionText) {
                $scope.todo.items.push({action: actionText, done: false});
            }
        })
        // 创建自定义过滤器
        todoApp.filter("checkedItems", function () {
            return function (items, showComplete) {
                var resultArr = [];
                angular.forEach(items, function (item) {
                    if (item.done == false || showComplete == true) {
                        resultArr.push(item);
                    }
                });
                return resultArr;
            }
        });

        todoApp.run(function ($http) {
            // 使用$http.get方法来创建一个HTTP.GET请求,向服务器请求todo.json文件
/*            调用success方法能够让指定一个将在发往服务器的Ajax请求已完成时被调用的函数,从而服务器获取到的JSON数据将会被解析并创建一个JavaScript对象,
            并传入给success函数作为data的参数,使用收到的data参数对模型进行更新*/
            $http.get("todo.json").success(function (data) {
                model.items = data;
            });
        });
    </script>
</head>
<body ng-controller="ToDoCtrl">
<div class="page-header">
    <h1>
        <!--创建视图1-->
        {
  {todo.user}}'s To Do List
        <span class="label label-default">total:{
  {todo.items.length}}</span>
        <span class="label label-default" ng-hide="incompleteCount() == 0" ng-class="warningLevel()">
            incompleteCount:{
  {incompleteCount()}}
        </span>

    </h1>
</div>
<div class="panel">
    <div class="input-group">
        <input class="form-control" ng-model="actionText"/>
        <span class="input-group-btn">
            <button class="btn btn-default" ng-click="addNewItem(actionText)">Add</button>
         </span>
    </div>
    <table class="table table-striped">
        <thead>
        <tr>
            <th>Description</th>
            <th>Done</th>
        </tr>
        </thead>
        <tbody>
        <!--创建视图2-->
        <!--使用自定义过滤器,对模型数据过滤和排序-->
        <tr ng-repeat="item in todo.items | checkedItems:showComplete | orderBy:'action'">
            <td>{
  {item.action}}</td>
            <!--使用双向绑定-->
            <td><input type="checkbox" ng-model="item.done"></td>
            <td>{
  {item.done}}</td>
        </tr>
        </tbody>
    </table>
    <div class="checkbox-inline">
        <!--增加一个复选框,使用ng-model指令来设置一个名为showComplete的模型值,该值通过表格中的ng-repeat指令传给自定义过滤器-->
        <label><input type="checkbox" ng_model="showComplete"> Show Complete</label>
    </div>
</div>
</body>
</html>

 

二、AngularJS应用剖析

(一)使用模块定义AngularJS组件

1. Module对象的成员方法

Name

Description

animation(name, factory)

Supports the animation feature

config(callback)

Registers a function that can be used to configure a module when it is loaded.

constant(key, value)

Defines a service that returns a constant value.

controller(name, constructor)

Creates a controller.

directive(name, factory)

Creates a directive, which extends the standard HTML vocabulary.

factory(name, provider)

Creates a service.

filter(name, factory)

Creates a filter that formats data for display to the user.

provider(name, type)

Creates a service.

name

Returns the name of the module.

run(callback)

 

Registers a function that is invoked after AngularJS has loaded and configured all of the modules.

service(name, constructor)

Creates a service.

value(name, value)

Defines a service that returns a constant value

2. 示例

<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
    <title>AngularJS Demo</title>
    <link href="../bootstrap.css" rel="stylesheet"/>
    <link href="../bootstrap-theme.css" rel="stylesheet"/>
    <script src="../angular.js"></script>
    <script>
        var myApp = angular.module("exampleApp", []);
        // 定义控制器
        myApp.controller("dayCtrl", function ($scope, days) {
            $scope.day = days.today;
        });
        myApp.controller("tomorrowCtrl", function ($scope, days) {
            $scope.day = days.tomorrow;
        });
/*        myApp.directive("highlight", function () {
            return function (scope, element, attrs) {
                if (scope.day == attrs["highlight"]) {
                    element.css("color", "red");
                }
            }
        });*/

/*        向指令的工厂函数里添加了一个$filter参数,这告诉AngularJS当我的函数被调用时要接受过滤器服务对象。
        $filter服务允许访问所有已定义的过滤器,包括前例中自定义的过滤器。通过名称获取过滤器:*/
        // 定义指令
        myApp.directive("highlight", function ($filter) {
            var dayFilter = $filter("dayName");

            return function (scope, element, attrs) {
                if (dayFilter(scope.day) == attrs["highlight"]) {
                    element.css("color", "red");
                }
            }
        });
        // 定义过滤器
        myApp.filter("dayName", function () {
            var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday",
                "Thursday", "Friday", "Saturday"];
            return function (input) {
                return angular.isNumber(input) ? dayNames[input] : input;
            };
        });
        var now = new Date();
        myApp.value("nowValue", now);
        // 定义服务
        myApp.service("days", function (nowValue) {
            this.today = nowValue.getDay();
            this.tomorrow = this.today + 1;
        });

    </script>
</head>
<body>
<div class="panel">
    <div class="page-header">
        <h3>AngularJS App</h3>
    </div>
    <h4 ng-controller="dayCtrl" highlight="Wednesday">
        Today is {
  {day || "(unknown)" | dayName}}
    </h4>
    <h4 ng-controller="tomorrowCtrl">
        Tomorrow is {
  {day || "(unknown)" | dayName}}
</div>
</body>
</html>

(二)使用模块组织代码

1. 示例

controllers.js

var controllersModule = angular.module("exampleApp.Controllers", []);

controllersModule.controller("dayCtrl", function ($scope, days) {
    $scope.day = days.today;
});

controllersModule.controller("tomorrowCtrl", function ($scope, days) {
    $scope.day = days.tomorrow;
});

filters.js

angular.module("exampleApp.Filters", []).filter("dayName", function () {
    var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"];
    return function (input) {
        return angular.isNumber(input) ? dayNames[input] : input;
    };
});

example.html

<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
    <title>AngularJS Demo</title>
    <link href="../bootstrap.css" rel="stylesheet" />
    <link href="../bootstrap-theme.css" rel="stylesheet" />
    <script src="../angular.js"></script>
    <script src="controllers.js"></script>
    <script src="filters.js"></script>
    <script>
        // 为了对主模块声明依赖,将每个模块的名称添加到一个数组中,并传给模块作为第二个参数
        var myApp = angular.module("exampleApp",
            ["exampleApp.Controllers", "exampleApp.Filters",
                "exampleApp.Services", "exampleApp.Directives"]);

        // Module.confg和Module.run方法注册了那些在AngularJS应用的生命周期的关键时刻所调用的函数。
        // 传给config方法的函数在当前模块被加载后调用,传给run方法的函数在所有模块被加载后调用。
        myApp.constant("startTime", new Date().toLocaleTimeString());
        myApp.config(function (startTime) {
            console.log("Main module config: " + startTime);
        });
        myApp.run(function (startTime) {
            console.log("Main module run: " + startTime);
        });

        angular.module("exampleApp.Directives", [])
            .directive("highlight", function ($filter) {

                var dayFilter = $filter("dayName");

                return function (scope, element, attrs) {
                    if (dayFilter(scope.day) == attrs["highlight"]) {
                        element.css("color", "red");
                    }
                }
            });

        var now = new Date();
        myApp.value("nowValue", now);

        angular.module("exampleApp.Services", [])
            .service("days", function (nowValue) {
                this.today = nowValue.getDay();
                this.tomorrow = this.today + 1;
            })
            .config(function() {
                console.log("Services module config: (no time)");
            })
            .run(function (startTime) {
                console.log("Services module run: " + startTime);
            });
    </script>
</head>
<body>
<div class="panel">
    <div class="page-header">
        <h3>AngularJS App</h3>
    </div>
    <h4 ng-controller="dayCtrl" highlight="Monday">
        Today is {
  {day || "(unknown)" | dayName}}
    </h4>
    <h4 ng-controller="tomorrowCtrl">
        Tomorrow is {
  {day || "(unknown)" | dayName}}
    </h4>
</div>
</body>
</html>

其中,config和run回调函数的调用顺序:

(1) The config callback on the exampleApp.Services module

(2) The config callback on the exampleApp module

(3) The run callback on the exampleApp.Services module

(4) The run callback on the exampleApp module

控制台输出结果:

 

三、使用绑定和模板指令

(一)数据绑定

1. 指令

Directive

Applied As

Description

ng-bind

Attribute, class

Binds the innerText property of an HTML element

ng-bind-html

Attribute, class

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值