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 检测、添加、移除样式(className)函数代码
Sep 08 Javascript
javascript Onunload与Onbeforeunload使用小结
Dec 31 Javascript
js实现身份证号码验证的简单实例
Feb 19 Javascript
手机端网页点击链接触发自动拨打或保存电话的示例代码
Aug 15 Javascript
js实现继承的5种方式
Dec 01 Javascript
JS检测页面中哪个HTML标签触发点击事件的方法
Jun 17 Javascript
jQuery Validate格式验证功能实例代码(包括重名验证)
Jul 18 jQuery
基于vue-cli 打包时抽离项目相关配置文件详解
Mar 07 Javascript
详解在React里使用&quot;Vuex&quot;
Apr 02 Javascript
js类的继承定义与用法分析
Jun 21 Javascript
微信小程序 生成携带参数的二维码
Oct 23 Javascript
vue在App.vue文件中监听路由变化刷新页面操作
Aug 14 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
mod_php、FastCGI、PHP-FPM等PHP运行方式对比
2015/07/02 PHP
php获取用户真实IP和防刷机制的实例代码
2018/11/28 PHP
chrome调试javascript详解
2015/10/21 Javascript
基于HTML+CSS+JS实现增加删除修改tab导航特效代码
2016/08/05 Javascript
基于jquery实现弹幕效果
2016/09/29 Javascript
Ext JS 实现建议词模糊动态搜索功能
2017/05/13 Javascript
使用Bootrap和Vue实现仿百度搜索功能
2017/10/26 Javascript
微信小程序之自定义组件的实现代码(附源码)
2018/08/02 Javascript
解决在vue项目中webpack打包后字体不生效的问题
2018/09/01 Javascript
微信小程序实现的日期午别医生排班表功能示例
2019/01/09 Javascript
jQuery事件委托代码实践详解
2019/06/21 jQuery
Vue中util的工具函数实例详解
2019/07/08 Javascript
原生js实现日历效果
2020/03/02 Javascript
Angular处理未可知异常错误的方法详解
2021/01/17 Javascript
[02:25]DOTA2英雄基础教程 生死判决瘟疫法师
2013/12/06 DOTA
[14:57]DOTA2 HEROS教学视频教你分分钟做大人-幽鬼
2014/06/13 DOTA
Windows和Linux下使用Python访问SqlServer的方法介绍
2015/03/10 Python
Python通过90行代码搭建一个音乐搜索工具
2015/07/29 Python
利用ctypes提高Python的执行速度
2016/09/09 Python
Python爬取三国演义的实现方法
2016/09/12 Python
Django实现基于类的分页功能
2019/10/31 Python
使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解
2020/01/25 Python
解决Pycharm中恢复被exclude的项目问题(pycharm source root)
2020/02/14 Python
pycharm设置python文件模板信息过程图解
2020/03/10 Python
python numpy矩阵信息说明,shape,size,dtype
2020/05/22 Python
pycharm导入源码的具体步骤
2020/08/04 Python
Python web框架(django,flask)实现mysql数据库读写分离的示例
2020/11/18 Python
西班牙英格列斯百货官网:El Corte Inglés
2016/09/25 全球购物
菲律宾票务网站:StubHub菲律宾
2018/04/21 全球购物
中文系学生自荐信范文
2013/11/13 职场文书
电子商务专员岗位职责
2013/12/11 职场文书
青年安全生产示范岗事迹材料
2014/05/04 职场文书
2014年班组建设工作总结
2014/12/01 职场文书
2014年留守儿童工作总结
2014/12/10 职场文书
优秀共青团员事迹材料
2014/12/25 职场文书
Java 使用类型为Object的变量指向任意类型的对象
2022/04/13 Java/Android