AngularJS如何从指令外部更改变量

如果我们使用 AngularJs 指令,我们可能需要更改其中的任何变量。
根据作用域的类型,方式有所不同。
如我们所知,作用域有 3 种类型:不继承、继承、隔离。

由于 AngularJS 现在是一个已弃用的框架,我们可以改用 JavaScript 现代框架,如 Vuejs、React 和 Angular。

让我们看看我们如何为每种类型的范围更改变量。

1.范围:false(不继承)

如果我们使用指令而不输入范围或者将范围输入为 false,则意味着指令不会继承范围,也不会隔离它。
指令将适用于我们当前的范围,这就是为什么更改指令中的任何变量都没有任何问题的原因。
我们可以在当前范围内的控制器/指令中更改我们想要的任何变量。

2.范围:true(继承)

在指令范围内:true 表示指令将从其父级继承范围。
它不是当前(父)作用域,也不是孤立作用域。
Angular 会创建一个新的作用域,它是当前作用域的子作用域,作为子作用域存在于当前作用域中。

如果我们尝试查看父作用域,我们将看到它的体系结构。
在父作用域中,我们将看到名为 $$childHead 的字段,这是它的第一个子作用域和字段 $$childTail,它是你的最后一个孩子范围。

如果我们有多个指令,在父作用域内 angular 将创建具有以下架构的所有子作用域:在第一个子作用域内,我们将看到类似 $$nextSibling 的内容,它是作用域的下一个。

如我们所知,我们可以使用第一个范围,更改它的变量,然后通过下一个范围并更改它的变量。

父作用域是这样的:

$$asyncQueue: Array[0]
$$childHead: $get.e.$new.a
   $$asyncQueue: Array[0]
   $$childHead: null
   $$childTail: null
   $$listeners: Object
   $$nextSibling: $get.e.$new.a
   $$prevSibling: null
   $$watchers: null
   $id: "004"
   $parent: $get.e.$new.a
   this: $get.e.$new.a
   __proto__: $get.e.$new.a
$$childTail: $get.e.$new.a
   $$asyncQueue: Array[0]
   $$childHead: null
   $$childTail: null
   $$listeners: Object
   $$nextSibling: null
   $$prevSibling: $get.e.$new.a
   $$watchers: null
   $id: "006"
   $parent: $get.e.$new.a
   this: $get.e.$new.a
   __proto__: $get.e.$new.a
$$listeners: Object
$$nextSibling: null
$$prevSibling: null
$$watchers: null
$id: "003"

例子

<!DOCTYPE html>
<html>
 <head>
   <title>www.onitroad.com</title>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
   <script>
      angular.module('test',[])
      .controller('testCtrl',function($scope){
            console.log($scope,'ctrl')
      })
         .directive('myTest',function(){
            return {
               restrict: 'EA',
               scope: false,
               compile: function(){
                  return function(scope){
                     console.log(scope,'directive');
                   }
           }
            }
         })
.directive('myIsolateTest',function(){
            return {
               restrict: 'EA',
               scope: true,
               compile: function(){
                  return function(scope){
                     console.log(scope,'directive');
                   }
           }
            }
         })
   </script>
 </head>
 <body>
   <div ng-app="test">
     <div ng-controller="testCtrl">
inherit parent scope
       <div my-test>scope id: {{$id}}</div>
       <div my-test>scope id: {{$id}}</div>
       <div my-test>scope id: {{$id}}</div>
<hr>
has own scope
       <div my-isolate-test>scope id: {{$id}}</div>
       <div my-isolate-test>scope id: {{$id}}</div>
       <div my-isolate-test>scope id: {{$id}}</div>
     </div>
   </div>
 </body>
</html>

在隔离作用域的情况下,指令作用域完全不知道其父作用域。

日期:2020-06-02 22:18:46 来源:oir作者:oir