AngularJS的Hello World

 

本篇体验AngularJS的Hello World,虽然简单,但体现了AnuglarJS的一些重要概念。

 

大致思路是这样的:

 

● 通常通过为hmtl元素添加AngularJS独有的属性来实现一些功能,比如ng-app, ng-controller


● 在js中,通常需要注册一个module,然后为module在注册controller等。AngularJS不仅仅有angular.js文件,还有其他的js文件,比如用来做路由配置的angular-route.js文件等,每一个文件包含module,使用AnularJS的过程就是让这些modules协同工作的过程

 

首先在页面引入AngularJS的核心js文件:

 

<script src="angular.min.js"></script>

 

接着,在定义js文件中为当前页面注册一个module:

 

var myApp = angular.module("helloApp",[])

 

以上,module的名称为helloApp, []数组用来存放与当前module有依赖关系的其它modules,比如['ngRoute','....']。

 

然后,为module注册controller

 

myApp.controller("TestController",['$scope',function($scope){
    $scope.hello = "Hello World!";            
}]);

 

以上,controller()的第一个参数是controller的名称,第二个参数的数组,数组的最后一个元素一定是匿名函数,其它元素是AngularJS的全局service,或者说是全局对象。需要注意的是:数组中的全局service的位置和名称必须和匿名函数的形参一一对应

 

我们还可以这样写:

 

myApp.controller("TestController", function($scope){
    $scope.hello = "Hello World!";  
});

 

不过,以上的写法在给js文件优化压缩的时候,会改变$scope变量的名称,比如替代为a,由于AngularJS只认$scope不认识a,这样会导致报错。所以,这种方法不推荐。

 

另外,全局service是以注入的方式被当前controller所使用。在AngularJS中,很多全局service都是通过依赖注入的方式被运用

 

最后,页面中要做3件事情。

 

1、使用ng-app声明当前module的名称

<html ng-app="helloApp">

 

2、使用ng-controller声明需要使用的controller

<body ng-controller="TestController">

 

3、使用{{}}显示$scope中的变量

<p>{{hello.name}}</p>

 

完整的代码如下:

 

<!doctype html>
<html ng-app="helloApp">
<head>
    <meta charset="UTF-8">
    <title>Untitled Document</title>
    <script src="angular.min.js"></script>
    <script>
        
        var myApp = angular.module("helloApp",[])
 
        myApp.controller("TestController",['$scope',function($scope){
            $scope.hello = "Hello World!";            
        }]);
        
    </script>
</head>
<body ng-controller="TestController">
   <p>{{hello}}</p>
</body>
</html>

 

当然,实际项目中$scope变量通常用来存储对象。比如:

 

        var myApp = angular.module("helloApp",[])
        
        //声明对象并对其赋值
        var messages = {};
        messages.name = 'Hello World!';
        
        myApp.controller("TestController",['$scope',function($scope){
            $scope.hello = messages;           
        }]);

 

在页面中按如下调用:

 

<p>{{hello.name}}</p>

 

当然与上面写法等同是:

 

<p ng-bind="hello.name"></p>

 

总结:留给我们的关键词是:module, module之间的协同和依赖, controller, 全局service依赖注入。       

posted @ 2015-10-01 10:26  Darren Ji  阅读(923)  评论(0编辑  收藏  举报

我的公众号:新语新世界,欢迎关注。