qiuri2008

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  步入正题。学习Angular,首先得了解、熟知、掌握它的四大核心特性。

  一、MVC模式

  

Model(模型):是应用程序中用于处理应用程序数据逻辑的部分,通常模型对象负责在数据库中存取数据。

View(视图):  用户看到并与之交互的界面  ,相当于html元素组成的页面。

Controller(控制器):是应用程序中处理用户交互的部分。通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。

MVC好处:职责清晰,代码模块化,它能为应用程序处理很多不同的视图,可以复用。后期维护方便。

AngularJS的MVC是借助$scope(作用域)实现的。

二、模块化与依赖注入

Angular 应用,可以说一切都是从模块开始的,下分五大模块,如图:

分别对应的是路由、过滤、指令、服务、控制器。

 引入方法:

<!doctype html>
<html ng-app="myapp">
    <head>
        <meta charset="utf-8">
    </head>
    <body>    
        <script>
            //[]内可以依赖angular内置模块,或者自定义模块注入,在路由、指令、服务中使用。具体的还得靠自己实践后明白。
            var Myapp = angular.module('myapp',['ngRoute']);

            //控制器
            Myapp.controller('name', function(){
                
            });

            //指令
            Myapp.directive('name', ['', function(){
                // Runs during compile
                return {
                    // name: '',
                    // priority: 1,
                    // terminal: true,
                    // scope: {}, // {} = isolate, true = child, false/undefined = no change
                    // controller: function($scope, $element, $attrs, $transclude) {},
                    // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
                    // restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
                    // template: '',
                    // templateUrl: '',
                    // replace: true,
                    // transclude: true,
                    // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
                    link: function($scope, iElm, iAttrs, controller) {
                        
                    }
                };
            }]);
        </script>
    </body>
</html>

 

 

三、指令

指令是Angular 中最有意味的一种特性,也是难点。先初步熟悉下,下几篇文章具体详解。

 

<!doctype html>
<html ng-app="MyModule">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <hello></hello>
        <div hello></div>
        <div class="hello"></div>
        <!-- directive:hello -->
        <div></div>
        <script>
            var MyApp = angular.module('MyModule',[]);

            MyApp.directive("hello", function() {
                return {
                    restrict: 'AEMC',
                    template: '<div>Hi everyone!</div>',
                    replace: true
                }
            });
        </script>
    </body>
</html>

四、双向数据绑定

先看一下单向数据绑定。

它的处理流程是这样的,首先呢,写好模板加上从服务器调取的数据结合在一起,通过数据绑定机制生成一段html标签,然后把这段标签显示出来。

它的缺点:html标签一旦生成,就无法改变,要是改变其中元素,或者新的数据更新,又要重新再来一遍把它替换掉,浪费时间,占用运行内存。

再看双向数据绑定。

它的想法是这样的,视图和数据是对应的,当视图上面的内容发生变化时,数据模型也跟着变化;当数据模型发生变化时,视图也跟着变化。

双向数据绑定经常应用的场景,表单的应用。。。。。。。。

posted on 2018-08-17 10:05  江召伟  阅读(392)  评论(0编辑  收藏  举报