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 相关文章推荐
jQuery ajax 路由和过滤器使用说明
Aug 02 Javascript
jquery实现的让超出显示范围外的导航自动固定屏幕最顶上
Sep 22 Javascript
window.addEventListener来解决让一个js事件执行多个函数
Dec 26 Javascript
js写的评论分页(还不错)
Dec 23 Javascript
jQuery+css3动画属性制作猎豹浏览器宽屏banner焦点图
Mar 16 Javascript
Backbone.js 0.9.2 源码注释中文翻译版
Jun 25 Javascript
jQuery使用$.ajax进行即时验证实例详解
Dec 11 Javascript
jQuery的Each比JS原生for循环性能慢很多的原因
Jul 05 Javascript
JS中split()用法(将字符串按指定符号分割成数组)
Oct 24 Javascript
vue中axios解决跨域问题和拦截器的使用方法
Mar 07 Javascript
this.$toast() 了解一下?
Apr 18 Javascript
IE11下CKEditor在Bootstrap Modal中下拉问题的解决
Sep 25 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 函数执行效率的小比较
2010/10/17 PHP
JavaScript创建命名空间的5种写法
2014/06/24 PHP
php提交post数组参数实例分析
2015/12/17 PHP
php实现图片压缩处理
2020/09/09 PHP
PHP实现限制域名访问的实现代码(本地验证)
2020/09/13 PHP
JS获取scrollHeight问题想到的标准问题
2007/05/27 Javascript
有效的捕获JavaScript焦点的方法小结
2009/10/08 Javascript
JS获取整个页面文档的实现代码
2011/12/15 Javascript
Javascript中valueOf与toString区别浅析
2013/03/19 Javascript
浅析jQuery 遍历函数,javascript中的each遍历
2016/05/25 Javascript
jQuery UI Bootstrap是什么?
2016/06/17 Javascript
js判断是否是手机页面
2017/03/17 Javascript
vue interceptor 使用教程实例详解
2018/09/13 Javascript
vue-cli脚手架搭建的项目去除eslint验证的方法
2018/09/29 Javascript
react同构实践之实现自己的同构模板
2019/03/13 Javascript
tweenjs缓动算法的使用实例分析
2019/08/26 Javascript
微信小程序实现录制、试听、上传音频功能(带波形图)
2020/02/27 Javascript
jQuery实现动态操作table行
2020/11/23 jQuery
微信小程序向Java后台传输参数的方法实现
2020/12/10 Javascript
python与caffe改变通道顺序的方法
2018/08/04 Python
Python Series从0开始索引的方法
2018/11/06 Python
Python常见数据结构之栈与队列用法示例
2019/01/14 Python
Python、 Pycharm、Django安装详细教程(图文)
2019/04/12 Python
keras中epoch,batch,loss,val_loss用法说明
2020/07/02 Python
CSS3实现同时执行倾斜和旋转的动画效果
2016/10/27 HTML / CSS
STRATHBERRY苏贝瑞包包官网:西班牙高级工匠手工打造
2020/11/10 全球购物
妇女儿童发展规划实施方案
2014/03/16 职场文书
医学生求职自荐书
2014/06/12 职场文书
2014年银行工作总结范文
2014/11/12 职场文书
关于拾金不昧的感谢信
2015/01/21 职场文书
老公写给老婆的检讨书
2015/05/06 职场文书
小鞋子观后感
2015/06/05 职场文书
2019年二手房买卖合同范本
2019/10/14 职场文书
python百行代码实现汉服圈图片爬取
2021/11/23 Python
教你修复 Win11应用商店加载空白问题
2021/12/06 数码科技
MySQL日期时间函数知识汇总
2022/03/17 MySQL