AngularJS语法详解


Posted in Javascript onJanuary 23, 2015

模板和数据的基本运作流程如下:

用户请求应用起始页面
用户的浏览器向服务器发起一次http连接,然后加载index.html页面,这个页面包含了模板
angular被加载到页面中,等待页面加载完成,查找ng-app指令,用来定义模板的边界
angular遍历模板,查找指定和绑定关系,将触发一些列动作:注册监听器、执行一些DOM操作、从服务器获取初始化数据。最后,应用将会启动起来,并将模板转换成DOM视图
连接到服务器去加载需要展示给用户的其他数据

显示文本

一种使用{{}}形式,如{{greeting}} 第二种ng-bind="greeting"

使用第一种,未被渲染的页面可能会被用户看到,index页面建议使用第二种,其余的页面可以使用第一种

表单输入

<html ng-app>

<head>

    <title>表单</title>

    <script type="text/javascript" src="angular.min.js"></script>

    <script type="text/javascript">

    function StartUpController($scope) {

        $scope.funding = {startingEstimate:0};

        computeNeeded = function() {

            $scope.funding.needed = $scope.funding.startingEstimate * 10;

        };

        $scope.$watch('funding.startingEstimate',computeNeeded); //watch model的变化

    }

    </script>

</head>

<body>

    <form ng-controller="StartUpController">

        Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">  //change的时候调用函数

        Recommendation: {{funding.needed}}

    </form>

</body>

</html>

在某些情况下,我们不想一有变化就立刻做出动作,而是要进行等待。例如:

<html ng-app>

<head>

    <title>表单</title>

    <script type="text/javascript" src="angular.min.js"></script>

    <script type="text/javascript">

    function StartUpController($scope) {

        $scope.funding = {startingEstimate:0};

        computeNeeded = function() {

            $scope.funding.needed = $scope.funding.startingEstimate * 10;

        };

        $scope.$watch('funding.startingEstimate',computeNeeded);//watch监视一个表达式,当这个表达式发生变化时就会调用一个回调函数

        $scope.requestFunding = function() {

            window.alert("Sorry,please get more customers first.")

        };

    }

    </script>

</head>

<body>

    <form ng-submit="requestFunding()" ng-controller="StartUpController">  //ng-submit

        Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">

        Recommendation: {{funding.needed}}

        <button>Fund my startup!</button>

    </form>

</body>

</html>

非表单提交型的交互,以click为例

<html ng-app>

<head>

    <title>表单</title>

    <script type="text/javascript" src="angular.min.js"></script>

    <script type="text/javascript">

    function StartUpController($scope) {

        $scope.funding = {startingEstimate:0};

        computeNeeded = function() {

            $scope.funding.needed = $scope.funding.startingEstimate * 10;

        };

        $scope.$watch('funding.startingEstimate',computeNeeded);

        $scope.requestFunding = function() {

            window.alert("Sorry,please get more customers first.")

        };

        $scope.reset = function() {

            $scope.funding.startingEstimate = 0;

        };

    }

    </script>

</head>

<body>

    <form ng-controller="StartUpController">

        Starting: <input ng-change="computeNeeded()" ng-model="funding.startingEstimate">

        Recommendation: {{funding.needed}}

        <button ng-click="requestFunding()">Fund my startup!</button>

        <button ng-click="reset()">Reset</button>

    </form>

</body>

</html>

列表、表格以及其他迭代型元素

ng-repeat会通过$index返回当前引用的元素序号。 示例代码如下:

<html ng-app>

<head>

    <title>表单</title>

    <script type="text/javascript" src="angular.min.js"></script>

    <script type="text/javascript">

    var students = [{name:'Mary',score:10},{name:'Jerry',score:20},{name:'Jack',score:30}]

    function StudentListController($scope) {

        $scope.students = students;
    }

    </script>

</head>

<body>

    <table ng-controller="StudentListController">

        <tr ng-repeat='student in students'>

            <td>{{$index+1}}</td>

            <td>{{student.name}}</td>

            <td>{{student.score}}</td>

        </tr>

    </table>

</body>

</html>

隐藏与显示
ng-show和ng-hide功能是等价的,但是运行效果正好相反。

<html ng-app>

<head>

<script type="text/javascript" src="angular.min.js"></script>

<script>

  function DeathrayMenuController($scope) {

    $scope.menuState = {show:false };//这里换成menuState.show = false 效果就显示不出来了。以后声明变量还是放在{}里面吧

    $scope.toggleMenu = function() {

      $scope.menuState.show = !$scope.menuState.show;

    };

  }

</script>

</head>

<body>

<div ng-controller='DeathrayMenuController'>

  <button ng-click='toggleMenu()'>Toggle Menu</button>

  <ul ng-show='menuState.show'>

    <li ng-click='stun()'>Stun</li>

    <li ng-click='disintegrate()'>Disintegrate</li>

    <li ng-click='erase()'>Erase from history</li>

  </ul>

</div>   

</body>

</html>

css类和样式

ng-class和ng-style都可以接受一个表达式,表达式执行的结果可能是如下取值之一:

表示css类名的字符串,以空格分隔
css类名数组
css类名到布尔值的映射
代码示例如下:

<html ng-app>

<head>

<style type="text/css">

    .error {

        background-color: red;

    }

    .warning {

        background-color: yellow;

    }

</style>

<script type="text/javascript" src="angular.min.js"></script>

<script>

  function HeaderController($scope) {

    $scope.isError = false;

    $scope.isWarning = false;
    $scope.showError = function() {

        $scope.messageText = "Error!!!!"

        $scope.isError = true;

        $scope.isWarning = false;

    }
    $scope.showWarning = function() {

        $scope.messageText = "Warning!!!"

        $scope.isWarning = true;

        $scope.isError = true;

    }

  }

</script>

</head>

<body>

<div ng-controller="HeaderController">

<div ng-class="{error:isError,warning:isWarning}">{{messageText}}</div>

    <button ng-click="showError()">Error</button>

    <button ng-click="showWarning()">Warning</button>

</div>

</body>

</html>

css类名到布尔值的映射
示例代码如下:

<html ng-app>

<head>

<style type="text/css">

    .selected {

        background-color: lightgreen;

    }

</style>

<script type="text/javascript" src="angular.min.js"></script>

<script>

    function Restaurant($scope) {

        $scope.list = [{name:"The Handsome",cuisine:"BBQ"},{name:"Green",cuisine:"Salads"},{name:"House",cuisine:'Seafood'}];
        $scope.selectRestaurant = function(row) {

            $scope.selectedRow = row;

        }

    }

</script>

</head>

<body>

<table ng-controller="Restaurant">

    <tr ng-repeat='restaurant in list' ng-click='selectRestaurant($index)' ng-class='{selected: $index==selectedRow}'>  //css类名到布尔值的映射,当模型属性selectedRow的值等于ng-repeat中得$index时,selectd样式就会被设置到那一行

        <td>{{restaurant.name}}</td>

        <td>{{restaurant.cuisine}}</td>

    </tr>

</table>

</body>

</html>
Javascript 相关文章推荐
javascript 日期常用的方法
Nov 11 Javascript
javascript实现简单的Map示例介绍
Dec 23 Javascript
javascript的日期对象、数组对象、二维数组使用说明
Dec 22 Javascript
js实现iframe自动自适应高度的方法
Feb 17 Javascript
Angular中的Promise对象($q介绍)
Mar 03 Javascript
jQuery Ajax中的事件详细介绍
Apr 16 Javascript
详解js中的apply与call的用法
Jul 30 Javascript
微信小程序图表插件(wx-charts)实例代码
Jan 17 Javascript
原生js实现轮播图的示例代码
Feb 20 Javascript
node 解析图片二维码的内容代码实例
Sep 11 Javascript
js实现随机点名程序
Sep 17 Javascript
详解js中的几种常用设计模式
Jul 16 Javascript
JQuery选择器绑定事件及修改内容的方法
Jan 23 #Javascript
angular中使用路由和$location切换视图
Jan 23 #Javascript
JavaScript中的类与实例实现方法
Jan 23 #Javascript
PHP中CURL的几个经典应用实例
Jan 23 #Javascript
Javascript闭包用法实例分析
Jan 23 #Javascript
JavaScript学习笔记之Function对象
Jan 22 #Javascript
JavaScript学习笔记之Cookie对象
Jan 22 #Javascript
You might like
PHP下利用header()函数设置浏览器缓存的代码
2010/09/01 PHP
如何在php中正确的使用json
2013/08/06 PHP
wordpress自定义url参数实现路由功能的代码示例
2013/11/28 PHP
PHP操作mysql数据库分表的方法
2016/06/09 PHP
php通过PHPExcel导入Excel表格到MySQL数据库的简单实例
2016/10/29 PHP
PHP检查网站是否宕机的方法示例
2017/07/24 PHP
laravel获取不到session的三种解决办法【推荐】
2018/09/16 PHP
php实现构建排除当前元素的乘积数组方法
2018/10/06 PHP
PHP array_shift()用法实例分析
2019/01/07 PHP
PHP中命名空间的使用例子
2019/03/22 PHP
jquery实现的超出屏幕时把固定层变为定位层的代码
2010/02/23 Javascript
jquery解析xml字符串简单示例
2014/04/11 Javascript
使用smartupload组件实现jsp+jdbc上传下载文件实例解析
2017/01/05 Javascript
解决Vue.js 2.0 有时双向绑定img src属性失败的问题
2018/03/14 Javascript
vue项目base64字符串转图片的实现代码
2018/07/13 Javascript
在webstorm开发微信小程序之使用阿里自定义字体图标的方法
2018/11/15 Javascript
vue列表数据发生变化指令没有更新问题及解决方法
2020/01/16 Javascript
如何基于jQuery实现五角星评分
2020/09/02 jQuery
详解JavaScript执行模型
2020/11/16 Javascript
[01:00:14]2018DOTA2亚洲邀请赛 4.6 淘汰赛 VP vs TNC 第三场
2018/04/10 DOTA
python用ConfigObj读写配置文件的实现代码
2013/03/04 Python
Python socket网络编程TCP/IP服务器与客户端通信
2017/01/05 Python
python将字符串转换成json的方法小结
2019/07/09 Python
python实现局域网内实时通信代码
2019/12/22 Python
python DataFrame转dict字典过程详解
2019/12/26 Python
基于Python下载网络图片方法汇总代码实例
2020/06/24 Python
CSS3旋转——彩色扇子兼容firefox浏览器
2013/06/04 HTML / CSS
德国婴儿推车和儿童安全座椅商店:BABYSHOP
2016/09/01 全球购物
意大利宠物用品购物网站:Bauzaar
2018/09/15 全球购物
幼儿园长自我鉴定
2013/10/17 职场文书
大学生入党思想汇报
2014/01/01 职场文书
服装设计专业自荐信
2014/06/17 职场文书
党的群众路线教育实践活动先进个人材料
2014/12/24 职场文书
工厂门卫岗位职责
2015/04/13 职场文书
2016年教师学习教师法心得体会
2016/01/20 职场文书
《活见鬼》教学反思
2016/02/24 职场文书