Angularjs:Angularjs使用心得
来源:互联网 发布:js修改css display 编辑:程序博客网 时间:2024/04/26 01:05
写在开头
从真正接触angularjs到现在,还没有一个月的时间,一直都处于遇坑填坑的状态。之前一直都在耳闻,未有实战的机会,现在项目中使用到了angularjs, 也便体会到双向绑定的好处,要充分利用起来,估计还得一段时间的填坑。
看angular的时候,社区里有这么一句话
Do not use angular as jQuery
这里并不是说jQuery不好,事实上jQuery极大了提高前端的开发。这里想表达的时,用充分利用angular的特点, 不要用jQuery的思维方式工作。
坑一
从$scope说起
每一个route对应着一个独立的controller
比如这样
..... .state('home', { templateUrl: 'path/to/yourfilename.html', controller: 'homeCtrl', absolute: true, resolve:{ ......... } }) .....
controller中,不得不提及的便是$scope。在刚接触的时候,还没来得及理解angular中controller的工作原理。通过代码,个人感觉可以类比一下,controller类似一个构造函数,$scope类似构造函数中的this属性.恩最初仅仅是凭代码,认为是这样的。后来发现,$scope与this不一定相等。代码如下:
<div ng-controller="ParentCtrl"> <a ng-click="logThisAndScope()">log "this" and $scope</a> - parent scope <div ng-controller="ChildCtrl"> <a ng-click="logThisAndScope()">log "this" and $scope</a> - child scope </div></div>
在parentCtrl中:
$scope.logThisAndScope = function() { console.log(this, $scope)}
通过以上代码,可以发现,点击第一个链接时,$scope与this的值相等,第二个链接不相等了。
demo
那么,this与 $ scope到底是怎样的一个关系呢?在JavaScript中,this的值永远都是跟当前函数的作用域相关的,在第二次点击中,函数的执行并不是在ChildCtrl中执行的,而是在ParentCtrl中执行的,而$scope是指定的controller绑定在一起的。
至于何时用$scope与this,这里待继续挖掘后,再来记录。
在controller中,我们经常会定义一些变量,然后通过view来绑定数据。然而,代码中,有个通病就是命名空间的问题了。
........ $scope.isOn = false; $scope.isShow = fasle; $scope.food = null; $scope.water = null //自行脑补 ........
假如这里,我们需要的变量比较多,还是以上面的方式进行变量申明的时候,一是阅读起来比较吃力,二是自己的写逻辑的时候,也比较散乱。写可读性代码也是咱们的能力之一啊。
这样写会不会稍微好点
.....$scope.switch = { isOn :false; isShow :fasle;};$scope.mainData = { food:null; water:null;};$scope.extraData = { info:null;};
把相关性的变量整理在一起,在后续写逻辑的时候,效率贵更快点,在绑定数据时, 也更加清晰,日后维护时,也比较轻松点。
继续谈$scope。
项目中UI框架用的是angular-material。在使用它的dialog时,一开始是这样写的。。
$scope.showModal = (ev) => { $mdDialog.show({ controller: modalCtrl, templateUrl: 'path/to/yourfilename.html', parent: angular.element(document.body), targetEvent: ev, clickOutsideToClose: true, }) };
前提是这样的,dialog的controller写在父级的controller中,父级的controller中有些变量,dialog中也需要用到。如果按照上面的方式写,是无法找到父级的环境。因为每个controller都是独立的,如果不指定继承关系,它就只能在当前的controller中寻找变量。
所以只需要指定它的继承关系即可,像这样:
$scope.showModal = (ev) => { $mdDialog.show({ controller: modalCtrl, templateUrl: 'path/to/yourfilename.html', parent: angular.element(document.body), targetEvent: ev, clickOutsideToClose: true, scope: $scope, preserveScope: true }) };
未完待续
- Angularjs:Angularjs使用心得
- angularJS $watch $timeout 使用心得
- AngularJS使用心得(持续更新中)
- AngularJS中ng-repeat使用心得
- AngularJs 一些心得
- angularJS开发心得总结
- AngularJS使用
- angularJS使用
- AngularJS
- angularjs
- Angularjs
- angularJS
- AngularJS
- AngularJS
- AngularJS
- AngularJs
- AngularJS
- AngularJs
- 微信UI项目:jQuery WeUI
- 2016SDAU课程练习一1005
- 游戏 “售饼雄才” 介绍
- apps被拒绝的各种理由以及翻译
- HDU 1814 POI 2001 Peaceful Commission 2-SAT
- Angularjs:Angularjs使用心得
- cmd无法识别javac命令
- 点灯的总结
- ios 观察者模式
- Android开发之ContentProvider结合LoaderManager加载数据
- JAVA内存泄漏问题处理方法经验总结
- gps协议
- Beautiful Year(cf)
- Struts2学习(一)