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 相关文章推荐
简单的无缝滚动程序-仅几行代码
May 08 Javascript
Jquery实现侧边栏跟随滚动条固定(兼容IE6)
Apr 02 Javascript
javascript学习笔记(六)数据类型和JSON格式
Oct 08 Javascript
jQuery网页版打砖块小游戏源码分享
Aug 20 Javascript
jQuery Mobile中的button按钮组件基础使用教程
May 23 Javascript
AngularJS操作键值对象类似java的hashmap(填坑小结)
Nov 12 Javascript
js实现图片放大展示效果
Aug 30 Javascript
浅析Vue实例以及生命周期
Aug 14 Javascript
详解在Node.js中发起HTTP请求的5种方法
Jan 10 Javascript
如何在JavaScript中谨慎使用代码注释
Jun 21 Javascript
js设置鼠标悬停改变背景色实现详解
Jun 26 Javascript
JS Ajax请求会话过期处理问题解决方法分析
Nov 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
解决cPanel无法安装php5.2.17
2014/06/22 PHP
ThinkPHP实现事务回滚示例代码
2014/06/23 PHP
laravel框架中间件 except 和 only 的用法示例
2019/07/12 PHP
thinkphp5.1框架容器与依赖注入实例分析
2019/07/23 PHP
laravel框架实现敏感词汇过滤功能示例
2020/02/15 PHP
不用写JS也能使用EXTJS视频演示
2008/12/29 Javascript
javascript 写类方式之二
2009/07/05 Javascript
Lazy Load 延迟加载图片的 jQuery 插件
2010/02/06 Javascript
js中复制行和删除行的操作实例
2013/06/25 Javascript
基于jquery的文字向上跑动类似跑马灯的效果
2014/09/22 Javascript
模仿password输入框的实现代码
2016/06/07 Javascript
js 实现数值的千分位及保存小数方法(推荐)
2016/08/01 Javascript
jQueryUI 拖放排序遇到滚动条时有可能无法执行排序的小bug及解决方案
2016/12/19 Javascript
Vue.js实现简单动态数据处理
2017/02/13 Javascript
浅谈vue项目可以从哪些方面进行优化
2018/05/05 Javascript
Nodejs 发布自己的npm包并制作成命令行工具的实例讲解
2018/05/15 NodeJs
Vue+Webpack完美整合富文本编辑器TinyMce的方法
2018/11/30 Javascript
从0到1构建vueSSR项目之node以及vue-cli3的配置
2019/03/07 Javascript
解决angular 使用原生拖拽页面卡顿及表单控件输入延迟问题
2020/04/21 Javascript
python检测服务器是否正常
2014/02/16 Python
python多线程操作实例
2014/11/21 Python
Python3模拟curl发送post请求操作示例
2019/05/03 Python
python 实现将list转成字符串,中间用空格隔开
2019/12/25 Python
Python Switch Case三种实现方法代码实例
2020/06/18 Python
你需要学会的8个Python列表技巧
2020/06/24 Python
Python实现打包成库供别的模块调用
2020/07/13 Python
Pycharm及python安装详细教程(图解)
2020/07/31 Python
长青弘远的面试题
2012/06/09 面试题
注塑工厂厂长岗位职责
2013/12/02 职场文书
自荐书4要点
2014/01/25 职场文书
幼儿教师师德承诺书
2014/05/23 职场文书
农村党支部书记四风问题个人对照检查材料
2014/09/21 职场文书
写景作文评语集锦
2014/12/25 职场文书
2015年基建工作总结范文
2015/05/23 职场文书
安全教育日主题班会
2015/08/13 职场文书
创业计划书之溜冰场
2019/10/25 职场文书