理解angularJS中作用域$scope
2015-09-24 15:35
615 查看
angularJS中作用域是什么
作用域(scope)是构成angularJS应用的核心基础,在整个框架中都被广泛使用,因此了解它如何工作是非常重要的应用的作用域是和应用的数据模型相关联的,同时作用域也是表达式执行的上下文
$scope对象是定义应用业务逻辑、控制器方法和视图属性的地方
作用域是视图和控制器之间的胶水,在应用将视图渲染并呈献给用户之前,视图中的模板会和作用域进行连接
作用域能做什么
提供观察者以监视数据模型的变化可以将数据模型的变化通知给整个应用,甚至是系统外的组件
可以进行嵌套,隔离业务功能和数据
给表达式提供运算时所需的执行环境
视图和$scope
angularJS启动并生成视图时,会将根ng-app元素同$rootScope进行绑定$rootScope是所有scope对象的最上层
$rootScope是angularJS中最接近全局作用域的对象。在rootScope上附加太多业 务逻并不是好主意,这与污染JavaScript的全局作用域是一样的,代码示例:
demo.html <!doctype html> <html ng-app="freefedApp"> <head> <title>angular应用demo</title> <script src="angular.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="helloCtrl"> <input ng-model="name" type="text" /> <button ng-click="changeText()">change</button> <div>{{ name }}</div> <div>apiKey:{{ apiKey }}</div> </div> </body> </html>
app.js /*声明module*/ var module = angular.module('freefedApp',[]).run(['$rootScope',function($rootScope){ /*freefedApp模块内都可以访问到这个模块全局变量*/ $rootScope.apiKey = 'abcdef97h5'; }]); /*声明控制器*/ module.controller('helloCtrl',['$scope',function($scope){ $scope.name = 'hello world'; $scope.changeText = function(){ $scope.name = 'hello dingdone'; }; /*监听数据模型的变化*/ $scope.$watch('name',function(newvalue,oldvalue){ }); }]);
相关文章推荐
- 如何写angularJS模块
- 如何搭建一个angularJS应用
- ng-repeat遍历空数组或无键名的数组问题的解决
- angularjs2.0 五分钟入门教程之typescript版本
- 学习笔记-AngularJs(七)
- angular form 验证
- angularjs承诺
- Angularjs中文版本开发指南发布
- AngularJS学习资源
- angularjs[1.4.3]
- AngularJs 构建复杂应用(二)
- angular form 验证 ngMessage
- 学习笔记-AngularJs(六)
- angular 自定义指令 link or controller
- angular Creating a Directive that Adds Event Listeners
- ExtJS vs AngularJS
- AngularJs学习html转义
- AngularJS 项目开发实战
- angular @ = &
- AngularJS体验式编程系列文章