2019独角兽企业重金招聘Python工程师标准>>>

理解控制器

在Angular中,一个控制器是一个javascript构造函数用于填充Angular作用域。

当一个控制器通过使用ng-controller指令附加到DOM上的时候,Angular将初始化一个新的Controller对象,使用指定的控制器构造函数。一个新的子作用域将可以作为一个参数$scope被注入到控制器构造函数。

控制器用于:

  • 配置作用域对象的初始化状态
  • 添加行为到作用域对象

不要将控制器用于:

  • 维护DOM - 控制器应该只包含业务逻辑。放置任何的展现逻辑到控制器中将极大的影响可测试性。
  • 格式化输入 - 应该使用angular表单控制器处理
  • 过滤输出 - 应该使用angular过滤器处理
  • 在多个控制器中共享代码或状态 - 应该使用angular service。

建立作用域对象的初始化状态

通常,当你创建一个应用你必须设置Angular作用域的初始化状态。你通过附加属性到$scope对象去设置作用域初始化状态。这些属性包括视图模型(这个模型将通过视图呈现)。作用域中的所有属性都将提供给在dom中注册了控制器的模板。

下面的例子演示了创建一个GreetingController,附加一个包含字符串'Hola!'的属性到作用域上。

var myApp = angular.module('myApp',[]);myApp.controller('GreetingController', ['$scope', function($scope) {$scope.greeting = 'Hola!';
}]);

我们创建一个Angular模块名称为myApp为我们的应用。然后我们添加控制器构造函数到模块,使用.controller方法。这样儿是保持控制器构造函数不放在全局作用域中。

我们使用一个行内注入标记去明确的声明Controller的依赖于Angular 提供的$scope服务。查看手册 Dependency Injection了解更多的信息。

我们附加我们的控制器到DOM使用ng-controller指令,greeting属性现在就可以数据绑定到模板了。

<div ng-controller="GreetingController">{{ greeting }}
</div>

添加行为到作用域对象

In order to react to events or execute computation in the view we must provide behavior to the scope. We add behavior to the scope by attaching methods to the $scope object. These methods are then available to be called from the template/view.

The following example uses a Controller to add a method to the scope, which doubles a number:

var myApp = angular.module('myApp',[]); myApp.controller('DoubleController', ['$scope', function($scope) { $scope.double = function(value) { return value * 2; };
}]);

Once the Controller has been attached to the DOM, the double method can be invoked in an Angular expression in the template:

<div ng-controller="DoubleController">Two times <input ng-model="num"> equals {{ double(num) }}
</div>

As discussed in the Concepts section of this guide, any objects (or primitives) assigned to the scope become model properties. Any methods assigned to the scope are available in the template/view, and can be invoked via angular expressions and ng event handler directives (e.g. ngClick).

Using Controllers Correctly

In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.

The most common way to keep Controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in Controllers via dependency injection. This is discussed in the Dependency Injection Services sections of this guide.

Associating Controllers with Angular Scope Objects

You can associate Controllers with scope objects implicitly via the ngController directive or $route service.

Simple Spicy Controller Example

To illustrate further how Controller components work in Angular, let's create a little app with the following components:

  • A template with two buttons and a simple message
  • A model consisting of a string named spice
  • A Controller with two functions that set the value of spice

The message in our template contains a binding to the spice model, which by default is set to the string "very". Depending on which button is clicked, the spice model is set to chili or jalapeño, and the message is automatically updated by data-binding.

  Edit in Plunker

index.html app.js

<div ng-controller="SpicyController"><button ng-click="chiliSpicy()">Chili</button><button ng-click="jalapenoSpicy()">Jalapeño</button><p>The food is {{spice}} spicy!</p>
</div>

Things to notice in the example above:

  • The ng-controller directive is used to (implicitly) create a scope for our template, and the scope is augmented (managed) by theSpicyController Controller.
  • SpicyController is just a plain JavaScript function. As an (optional) naming convention the name starts with capital letter and ends with "Controller".
  • Assigning a property to $scope creates or updates the model.
  • Controller methods can be created through direct assignment to scope (see the chiliSpicy method)
  • The Controller methods and properties are available in the template (for the <div> element and its children).

Spicy Arguments Example

Controller methods can also take arguments, as demonstrated in the following variation of the previous example.

  Edit in Plunker

index.html app.js

<div ng-controller="SpicyController"><input ng-model="customSpice"><button ng-click="spicy('chili')">Chili</button><button ng-click="spicy(customSpice)">Custom spice</button><p>The food is {{spice}} spicy!</p>
</div>

Notice that the SpicyController Controller now defines just one method called spicy, which takes one argument called spice. The template then refers to this Controller method and passes in a string constant 'chili' in the binding for the first button and a model property customSpice (bound to an input box) in the second button.

Scope Inheritance Example

It is common to attach Controllers at different levels of the DOM hierarchy. Since the ng-controller directive creates a new child scope, we get a hierarchy of scopes that inherit from each other. The $scope that each Controller receives will have access to properties and methods defined by Controllers higher up the hierarchy. See Understanding Scopes for more information about scope inheritance.

  Edit in Plunker

index.html app.css app.js

<div class="spicy"><div ng-controller="MainController"><p>Good {{timeOfDay}}, {{name}}!</p><div ng-controller="ChildController"><p>Good {{timeOfDay}}, {{name}}!</p><div ng-controller="GrandChildController"><p>Good {{timeOfDay}}, {{name}}!</p></div></div></div>
</div>

Notice how we nested three ng-controller directives in our template. This will result in four scopes being created for our view:

  • The root scope
  • The MainController scope, which contains timeOfDay and name properties
  • The ChildController scope, which inherits the timeOfDay property but overrides (hides) the name property from the previous
  • The GrandChildController scope, which overrides (hides) both the timeOfDay property defined in MainController and the nameproperty defined in ChildController

Inheritance works with methods in the same way as it does with properties. So in our previous examples, all of the properties could be replaced with methods that return string values.

Testing Controllers

Although there are many ways to test a Controller, one of the best conventions, shown below, involves injecting the $rootScope and$controller:

Controller Definition:

var myApp = angular.module('myApp',[]); myApp.controller('MyController', function($scope) { $scope.spices = [{"name":"pasilla", "spiciness":"mild"},{"name":"jalapeno", "spiciness":"hot hot hot!"},{"name":"habanero", "spiciness":"LAVA HOT!!"}]; $scope.spice = "habanero";
});

Controller Test:

describe('myController function', function() { describe('myController', function() {var $scope; beforeEach(module('myApp')); beforeEach(inject(function($rootScope, $controller) { $scope = $rootScope.$new(); $controller('MyController', {$scope: $scope});})); it('should create "spices" model with 3 spices', function() { expect($scope.spices.length).toBe(3);}); it('should set the default value of spice', function() { expect($scope.spice).toBe('habanero');});});
});

If you need to test a nested Controller you need to create the same scope hierarchy in your test that exists in the DOM:

describe('state', function() {var mainScope, childScope, grandChildScope; beforeEach(module('myApp')); beforeEach(inject(function($rootScope, $controller) { mainScope = $rootScope.$new(); $controller('MainController', {$scope: mainScope}); childScope = mainScope.$new(); $controller('ChildController', {$scope: childScope}); grandChildScope = childScope.$new(); $controller('GrandChildController', {$scope: grandChildScope});})); it('should have over and selected', function() { expect(mainScope.timeOfDay).toBe('morning'); expect(mainScope.name).toBe('Nikki'); expect(childScope.timeOfDay).toBe('morning'); expect(childScope.name).toBe('Mattie'); expect(grandChildScope.timeOfDay).toBe('evening'); expect(grandChildScope.name).toBe('Gingerbread Baby');});
});

tips:

本文由wp2Blog导入,原文链接:http://devonios.com/3%e3%80%81angular-js-%e5%ad%a6%e4%b9%a0%e7%ac%94%e8%ae%b0-controllers.html

转载于:https://my.oschina.net/yangyan/blog/859235

3、Angular JS 学习笔记 – Controllers [翻译中]相关推荐

  1. 4、Angular JS 学习笔记 – 创建自定义指令 [翻译中]

    2019独角兽企业重金招聘Python工程师标准>>> 创建自定义指令 注意:本指南是针对已经熟悉AngularJS基础的开发者.如果您只是想要开始,建议您先去看教程.如果你在寻找指 ...

  2. js学习笔记——在html中嵌入脚本

    一.在html中嵌入js代码: 在html文件里嵌入js代码主要有四种形式: 第一种是通过<script></script>标记,这种一般用来定义一些函数,放在body外: 第 ...

  3. JS学习笔记——高级编程中compose函数的介绍和基本实现

    1.前言 在之前探讨redux的中间件的时候,applyMiddleware源码中有遇到过compose()函数,当时不太明白起作用,所以就上网好好查了一下,做了个总结. 2.普通函数 在函数式编程当 ...

  4. JS学习笔记六:js中的DOM操作

    1. JS学习笔记六:js中的DOM操作 文章目录 1. JS学习笔记六:js中的DOM操作 1.1. 获取Dom节点 1.2. 元素属性的操作方式 1.3. DOM节点的创建.插入和删除 1.4. ...

  5. 唤醒手腕 - 前端服务器端开发 Node.Js 学习笔记(学习中,更新中)

    唤醒手腕 - Node.Js 学习笔记 唤醒手腕个人的学习记录,时间在2021年12月13日 ~ 2021年12月14日,学习方式看官方文档和B站视频,如有错误或者代码问题的地方,欢迎C站大佬能够帮忙 ...

  6. ArcGIS JS 学习笔记4 实现地图联动

    原文:ArcGIS JS 学习笔记4 实现地图联动 1.开篇 守望屁股实在太好玩了,所以最近有点懒,这次就先写个简单的来凑一下数.这次我的模仿目标是天地图的地图联动. 天地的地图联动不仅地图有联动,而 ...

  7. node.js学习笔记

    # node.js学习笔记标签(空格分隔): node.js---## 一 内置模块学习 ### 1. http 模块 ``` //1 导入http模块 const http =require('ht ...

  8. SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用

    1. freemarker引擎的使用 如果你使用的是idea或者eclipse中安装了sts插件,那么在新建项目时就可以直接指定试图模板 如图: 勾选freeMarker,此时springboot项目 ...

  9. WebGL three.js学习笔记 6种类型的纹理介绍及应用

    WebGL three.js学习笔记 6种类型的纹理介绍及应用 本文所使用到的demo演示: 高光贴图Demo演示 反光效果Demo演示(因为是加载的模型,所以速度会慢) (一)普通纹理 计算机图形学 ...

最新文章

  1. 180608-Git工具之Stash
  2. HDU - 1394 Minimum Inversion Number(树状数组)
  3. 原创-WINDOWS SERVER 2008 WEB服务器安装配置
  4. draconet 1.6-release-1 (1.6.3.0)
  5. 有时候能讲出来,比沉默要好吧
  6. the server is not ready for publishing.Please check if the Publishing Tools on the server
  7. mysql 提取字符串首字母_SQL获取字段字符串中文首字母
  8. Linq之IQueryable与IEnumerable
  9. 开关电源(Switch Regulator)---Buck
  10. 【大数据入门核心技术-HBase】(九)Hbase协处理器coprocessor
  11. AIX PowerPC体系结构及其溢出技术学习笔记
  12. 40st-m00330 型伺服电机STM32单片机PWM脉冲控制
  13. 服务器 最大连接数:
  14. java 判断文件名合法_java用正则方法验证文件名是否合法
  15. Vimium--通过键盘就能更高效快速便捷地上网
  16. 【虹科分享】影响数字化仪精度的因素
  17. 【灵动MM32-姿态角解算】移植MPU6050-DMP库实现姿态角PRY解算
  18. 关于在react项目中img标签src的路径问题
  19. 服务器硬件RAID性能横评(3)
  20. python学习,王者荣耀管理系统(千锋教育)

热门文章

  1. POI实现Excel导出时常用方法说明
  2. DOS介绍以及常用命令
  3. ajax mysql项目 react_Github MIT开源银行电子支付系统(ReactJS+Nodejs+Mysql)
  4. smart700iev3 程序下载设置_西门子PLC基础:S7-200 SMART PLC程序下载
  5. 神策 FM |「聚焦」细分市场是独角兽诞生的营销关键
  6. 如何帮助企业优化商业模式?看精益数据分析的“欺”与“破”
  7. 神策数据荣获“年度最具影响力大数据服务厂商”奖项
  8. 巨头纷纷布局,机器视觉迎来黄金期
  9. Spring4 学习系列之——jdbc事务的基本实现和了解
  10. DPM2010恢复整个邮箱数据库