如何在angular中只对某些变量使用父作用域,而对其他变量保持隔离

How to use parent scope only for some variables in angular, and keep the other variables isolated

本文关键字:变量 作用域 其他 隔离 angular      更新时间:2023-09-26

mydirective是一个孤立的作用域指令。这是因为我不想将指令的所有逻辑暴露给指令之外的任何地方。但是我想在指令之外访问输入数据。

<div mydirective>
   <input ng-model="data.input">
</div>
<div mydirective>
   <input ng-model="otherdata.public">
   <input ng-model="more.than.one">
</div>
{{data.input}}
{{otherdata.public}}

我更喜欢HTML不改变就能工作,只改变指令代码。所以我想知道如何创建指令

app.directive('mydirective',function(){ return {
 scope:true,
 controller:function($scope){
     $scope.this_variable_needs_to_be_private=true
 },
 transclude:true
}})

编辑:add translude:true。但是我仍然没有答案

考虑使用$transclude函数并使用$scope.$new():

创建自己的childScope

(function() {
  "use strict";
  angular.module("myApp", [])
    .controller("Controller1", ['$scope', Controller1])
    .directive("mydirective", [mydirective]);
  function Controller1($scope) {
    $scope.data = {
      input: 'data.input'
    };
    $scope.otherdata = {
      public: 'otherdata.public'
    };
    $scope.more = {
      than: {
        one: 'more.than.one'
      }
    }
  }
  function mydirective() {
    function _link($scope, $element, $attrs, controller, $transclude) {
      var childScope = $scope.$new(); //create a childScope
      //$scope.this_variable_needs_to_be_private = true; //<-- doing this would add it to public parent scope
      childScope.this_variable_needs_to_be_private = true; //<-- this puts it only on this directive's childscope
      // See: https://docs.angularjs.org/api/ng/service/$compile#transclusion
      $transclude(childScope, function(clone, scope) { //transcluding with our childScope
        $element.append(clone); //appending the clone of our content;
      });
    }
    return {
      transclude: true,
      link: _link
    };
  }
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Controller1">
  <div mydirective>
    <input ng-model="data.input">
    <br /><strong>this_variable_needs_to_be_private:</strong> {{this_variable_needs_to_be_private}}
  </div>
  <br />
  <div mydirective>
    <input ng-model="otherdata.public">
    <input ng-model="more.than.one">
    <br /><strong>this_variable_needs_to_be_private:</strong> {{this_variable_needs_to_be_private}}
  </div>
  <hr />
  <strong>data.input:</strong> {{data.input}}
  <br /><strong>otherdata.public:</strong> {{otherdata.public}}
  <br /><strong>this_variable_needs_to_be_private:</strong> {{this_variable_needs_to_be_private}}
</div>

$transclude的进一步阅读:https://stackoverflow.com/a/13184889/446030.

要访问指令的隔离作用域变量,可以使用单向或双向数据绑定,如下所示:

app.directive('mydirective',function(){ return {
 scope:{var1:"=outerVar"},
 controller:function($scope){
     $scope.var1='I am accessible outside...';
 }
}})

子作用域的变量无论如何在父作用域中是不可见的。您需要在隔离作用域中使用父作用域的变量来在它们之间进行通信。