javascript
[AngularJS] 理解AngularJS Directive中的Scope
默認(rèn)情況下, AngluarJS不會(huì)為在一個(gè)Controller下的Directive創(chuàng)建一個(gè)單獨(dú)的作用域(Scope). 這個(gè)Directive中的所有關(guān)于$scope的變量都是在它的Controller中定義, 并且會(huì)被其他的在同一Controller中的Directive所共享, 例如以下代碼:
<script>(function(angular) {angular.module('zzIsolateScopeTest', []).directive("directiveOne", function () {return {link : function($scope, $element, $attr) {$scope.site = "騰訊";}};}).directive("directiveTwo", function () {return {link : function($scope, $element, $attr) {$scope.site = "博客";}};}).controller("mainController", function ($scope) {$scope.site = "百度";});})(window.angular);</script> <div data-ng-controller="mainController"> <div class="row"><div class="col-md-3"><a data-directive-one class="btn btn-default btn-block">{{site}}</a></div></div><div class="row"><div class="col-md-3"><a data-directive-two class="btn btn-default btn-block">{{site}}</a></div></div> </div>打開頁面的結(jié)果是兩個(gè)"博客"鏈接的按鈕. 這是因?yàn)镈irectiveTwo在最后將site的值修改為了"博客", 并且影響到了DirectiveOne原來所修改成的值"騰訊".
AngluarJS引入isloate scope的概念, 使得每個(gè)Directive都能擁有自己的$scope變量, 從而不會(huì)在多個(gè)Directive之間因共享變量而造成數(shù)據(jù)錯(cuò)誤. 使用isolate scope的方法很簡單, 只需要在Directive的代碼中寫入一個(gè)屬性即可:
scope : {}示例代碼如下:
<script>(function(angular) {angular.module('zzIsolateScopeTest', []).directive("directiveOne", function () {return {scope : {},link : function($scope, $element, $attr) {$scope.site = "騰訊";}};}).directive("directiveTwo", function () {return {scope : {},link : function($scope, $element, $attr) {$scope.site = "博客";}};}).controller("mainController", function ($scope) {$scope.site = "百度";});})(window.angular);</script>通過這樣的方式, directive-one和directive-two都擁有了自己的$scope, 也就是說, 它們將不再使用mainController中的$scope. 那么做這樣的修改之后, 頁面將會(huì)出現(xiàn)什么結(jié)果呢?
答案是頁面上出現(xiàn)兩個(gè)"百度"鏈接按鈕.
如上面所說的, 當(dāng)directive擁有自己的$scope之后, 將不會(huì)影響mainController中的$scope, 所以, 這里的兩個(gè)占位符自然就mainController中的site值來填充. 也就是"百度".
?
轉(zhuǎn)載于:https://www.cnblogs.com/AmusementPark/p/4293006.html
總結(jié)
以上是生活随笔為你收集整理的[AngularJS] 理解AngularJS Directive中的Scope的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDFS分布式文件系统设计思想
- 下一篇: CentOS 6.4 命令行 安装 VM