在上一节讲完了关于应用开发中如数据绑定,加入样式一类的基础操作后,接下来,将在应用中,与控制其有关的一些事件。。。

一、UI和控制器的分离

我们须要明白控制器在应用中的三个作用:

【1】在应用模型中设置初始状态

【2】通过$scope对象向视图(UI模版)暴露函数和模型

【3】监视模型发生变化的其它部分并做出对应的动作

二、公布scope中的数据模型

传递给控制器的$scope对象是一种用来向视图暴露模型数据的机制。在我们构建的应用中可能有其它数据,可是通过scope传递这些属性时,angular仅仅考虑模型部分。

在之前的荔枝中,我们常常看到$scope构建的数据实例,而这一过程是在控制器中完毕,在这里,我们也能够通过一些间接的方法从模版建立模型。

1.使用表达式:因为表达式在可它们关联的控制器中运行,所以在表达式中设置属性和控制器中设置属性是一致的。即能够例如以下这么做

<button ng-click='count=3'>Set count to three</button>

其等同于

<div ng-controller='CountController'>
<button ng-click='setCount()'>Set count to three</button>
</div>

控制器定义

function CountController($scope) {
$scope.setCount = function() {
$scope.count=3;
}
}

2.通过ng-model进行一个数据绑定

三、用$watch观察模型变化

$watch(watchFn, watchAction, deepWatch)

该函数每一个參数具体内容

watchFn:这个參数是angualr表达式字符串或返回监控模型的当前值的函数,该表达式会被运行多次

watchAction:这是一个函数或者表达式,当watchFn变化时将调用他们,函数形式而言,它有watchFn的新旧值,及一个$scope引用,函数前面function(newValue,oldValue,scope)

deepWatch:这是一个可选的布尔參数,假设设置成true,angualr将监视对象每一个属性的变化

接下的栗子是之前购物车的升级版

<div ng-controller="CartController">
<div ng-repeat="item in items">
<span>{{item.title}}</span>
<input ng-model="item.quantity">
<span>{{item.price | currency}}</span>
<span>{{item.price * item.quantity | currency}}</span>
</div>
<div>Total: {{totalCart() | currency}}</div>
<div>Discount: {{bill.discount | currency}}</div>
<div>Subtotal: {{subtotal() | currency}}</div>
</div>

CartController:

function CartController($scope) {
$scope.bill = {};
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
$scope.totalCart = function() {
var total = 0;
for (var i = 0, len = $scope.items.length; i < len; i++) {
total = total + $scope.items[i].price * $scope.items[i].quantity;
}
return total;
}
$scope.subtotal = function() { return $scope.totalCart() - $scope.bill.discount;
};
function calculateDiscount(newValue, oldValue, scope) {
$scope.bill.discount = newValue > 100 ? 10 : 0;
}
$scope.$watch($scope.totalCart, calculateDiscount);
}

注意:在totalCart()建立一个监视,totalCart()用于计算该支付的总额,每当其发生变化时,watch函数就会调用calculateDiscount(),然后我们设置对这个值适当的折扣。假设总值达昱100$,就设置折扣为10$,否则为0;

上述结果

对于watch性能,我们还须要注意一些潜在的性能问题

在上述样例中,尽管其可以正常的执行,但假设我们在totoalCart()加一个调试的断电,你将会看到它被调用了六次才渲染页面,而在代码中我们非常easy跟踪到三次,

1.模版中{{totalCart|currency}}

2.Subtotal()函数

3.$watch()函数

而angualr为了验证传递的模型变化已经全然传递,会再执行多一次,所以总共执行六次,而这样的情况非常easy造成一个循环依赖。所以我们提供了下面的集中解决的方法

一种是在数组的每一个元素上创建爱你$watch监控变化,不过这样不过只计算了$scope属性中的total,discount,subtotal

<div>Total: {{bill.total | currency}}</div>
<div>Discount: {{bill.discount | currency}}</div>
<div>Subtotal: {{bill.subtotal | currency}}</div>

然后在控制器中,我们监视数组的元素,一旦数组发生不论什么变化,均会调用函数又一次计算总价

function CartController($scope) {
$scope.bill = {};
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
var calculateTotals = function() {
var total = 0;
for (var i = 0, len = $scope.items.length; i < len; i++) {
total = total + $scope.items[i].price * $scope.items[i].quantity;
}
$scope.bill.totalCart = total;
$scope.bill.discount = total > 100 ? 10 : 0;
$scope.bill.subtotal = total - $scope.bill.discount;
};
$scope.$watch('items', calculateTotals, true);
}

注意:在$scope指定了一个字符串的items,items将作为表达式在调用它的$scope作用域中运行

然后因为我们监视数组中的全部项,angualar不得不正确它进行一份拷贝用于对照,假设遇到一个具有非常多元素的列表时,可能会导致执行效率减少

所以我们能够给$watch仅仅传一个用于又一次计算属性的watchFn

$scope.$watch(function() {
var total = 0;
for (var i = 0; i < $scope.items.length; i++) {
total = total + $scope.items[i].price * $scope.items[i].quantity;
}
$scope.bill.totalCart = total;
$scope.bill.discount = total > 100 ? 10 : 0;
$scope.bill.subtotal = total - $scope.bill.discount;
});

四、组织模块的注入:

函数 定义
provider(name,object OR constructor()) 可配置,有复杂逻辑的服务,可用于构造函数
factory(name,$getFunction()) 不可配置,有复杂逻辑的服务,定义一个函数,调用时返回服务实例
service(name,constructor()) 具有简单逻辑,用于创建服务实例

在这里,我们利用之前讨论过的items演示样例使用factory()

// Create a module to support our shopping views
var shoppingModule = angular.module('ShoppingModule', []);
// Set up the service factory to create our Items interface to the
// server-side database
shoppingModule.factory('Items', function() {
var items = {};
items.query = function() {
// In real apps, we'd pull this data from the server...
return [
{title: 'Paint pots', description: 'Pots full of paint', price: 3.95}, {title: 'Polka dots', description: 'Dots with polka’, price: 2.95},
{title: 'Pebbles', description: 'Just little rocks', price: 6.95}
];
};
return items;
});
<html ng-app='ShoppingModule'>
<body ng-controller="ShoppingController">
<h1>Shop!</h1>
<table> <tr ng-repeat=”item in items”></tr>
<td>{{item.title}}</td>
<td>{{item.description}}</td>
<td>{{item.price | currency}}</td>
</tr>
</table>
</div>

五、用过滤器过滤数据

过滤器同意你申明怎样展示给用户的数据转换后插入到你的模版中。

{{ expression | filterName : parameter1 : ...parameterN }}

当中expression为随意表达式,filterName为你想用的过滤器的名称,传递给过滤器的參数用冒号隔开,

而angular有几个自带过滤器如:date,number,uppercase等,在这里就不多介绍,主要我们来学习假设自己创建一个自己定义过滤器

以下样例是通过filter()函数构造一个名为titleCase的过滤器,其作用是将句子中每一个单词的首字母大写

var homeModule = angular.module('HomeModule', []);
homeModule.filter('titleCase', function() {
var titleCaseFilter = function(input) {
var words = input.split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
}
return words.join(' ');
};
return titleCaseFilter;
});

相应的HTML模版

<body ng-app='HomeModule' ng-controller="HomeController">
<h1>{{pageHeading | titleCase}}</h1>
</body>

通过控制器赋值给模型变量

function HomeController($scope) {
$scope.pageHeading = 'behold the majesty of your page title';
}

执行结果例如以下图

angularjs入门学习【应用剖析中篇】的更多相关文章

  1. Angularjs入门学习一 简介

    本系列文章是从头开始学习angularjs,下文中用ng表示angularjs,要知道从以为根深蒂固的jquery开发者转变开发思想,确实需要一段时间,下面介绍以下 angularjs,我也是参考网上 ...

  2. AngularJS入门学习

    初识: {{}}   这种双层花括号的语法称之为:插值语法:也可以说是 标识符:AngularJS 主要就是使用这种方法进行数据绑定 ng-module="name"   在ng的 ...

  3. angularjs入门学习【指令篇】

    一.首先我们来了解下指令API 属性 含义 restrict 申明标识符在模版中作为元素,属性,类,凝视或组合,怎样使用 priority 设置模版中相对于其它标识符的运行顺序 Template 指定 ...

  4. 跟我学AngularJs:AngularJs入门及第一个实例

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:主要给大家介绍了AngularJs及其特性,并以3个实例来做说明. 本教程使用Angul ...

  5. canvas学习笔记(中篇) -- canvas入门教程-- 颜色/透明度/渐变色/线宽/线条样式/虚线/文本/阴影/图片/像素处理

    [中篇] -- 建议学习时间4小时  课程共(上中下)三篇 此笔记是我初次接触canvas的时候的学习笔记,这次特意整理为博客供大家入门学习,几乎涵盖了canvas所有的基础知识,并且有众多练习案例, ...

  6. AngularJS的学习网站及相关资源整理

    学习angularjs的网站及相关资源的整理,会不断更新. angularJs的官网:https://angularjs.org/       API文档:https://docs.angularjs ...

  7. 【转载】图灵AngularJS入门教程

    摘自图灵的AngularJS入门教程:http://www.ituring.com.cn/article/13471 感觉非常不错,所以推荐到首页一下! (一)Hello World! 开始学习Ang ...

  8. libevent的入门学习-库的安装【转】

    转自:https://blog.csdn.net/lookintosky/article/details/61658067 libevent的入门学习-库的安装最近开始接触Linux应用层的东西,发现 ...

  9. 《AngularJS入门与进阶》图书简介

    一.图书封面 二.图书CIP信息 图书在版编目(CIP)数据 AngularJS入门与进阶 / 江荣波著. – 北京 : 清华大学出版社, 2017 ISBN 978-7-302-46074-9 Ⅰ. ...

随机推荐

  1. android.view.ViewRootImpl$CalledFromWrongThreadException错误处理

    一般情况下,我们在编写android代码的时候,我们会将一些耗时的操作,比如网络访问.磁盘访问放到一个子线程中来执行.而这类操作往往伴随着UI的更新操作.比如说,访问网络加载一张图片 new Thre ...

  2. 再一次见证mssql中in 与exist的区别

    见下面代码 /*+' select * from '+@strDBName +'.dbo.m_aic where nodeid not in(select nodeid from @tmpAIC) ' ...

  3. Asp.Net Core(.net内核)

    Asp.Net Core(.net内核) //----------------Day1----------------一章    Web基本原理 1节课程说明 web窗体--设计界面--加法使用Chr ...

  4. hdu 1026 Ignatius and the Princess I(优先队列+bfs+记录路径)

    以前写的题了,现在想整理一下,就挂出来了. 题意比较明确,给一张n*m的地图,从左上角(0, 0)走到右下角(n-1, m-1). 'X'为墙,'.'为路,数字为怪物.墙不能走,路花1s经过,怪物需要 ...

  5. 程序破解之 API HOOK技术 z

    API HOOK,就是截获API调用的技术,在程序对一个API调用之前先执行你的函数,然后根据你的需要可以执行缺省的API调用或者进行其他处理,假设如果想截获一个进程对网络的访问,一般是几个socke ...

  6. 从表中随机返回n条记录

    创建测试用表: CREATE OR REPLACE VIEW V AS SELECT 'a' AS c FROM dual UNION ALL SELECT 'b' AS c FROM dual UN ...

  7. webstrom11 激活,webstorm 2016.1激活

    http://15.idea.lanyus.com/  webstorm11注册激活,你值得拥有 webstorm 2016.1 最新激活方式:http://blog.lanyus.com/archi ...

  8. Python对象体系揭秘

    Guido用C语言创造了Python,在Python的世界中一切皆为对象. 一.C视角中的Python对象 让我们一起追溯到源头,Python由C语言实现,且向外提供了C的API http://doc ...

  9. 【跟我一起学Python吧】Python的包管理工具

    刚开始学习Python时,在看文档和别人的blog介绍安装包有的用easy_install, setuptools, 有的使用pip,distribute,那麽这几个工具有什么关系呢,看一下下面这个图 ...

  10. mysql的登录密码带特殊符号登录不进去的问题

    eg : mysqldump -u root -p)P:9 ${dbname} > $dataPath$filename 当我将数据库的数据每天进行自动导出时,需要带上密码,但 ) 是一个特殊符 ...