【问题标题】:AngularJS custom directives - controller variables 'crosstalk'AngularJS 自定义指令 - 控制器变量“串扰”
【发布时间】:2015-04-27 19:18:38
【问题描述】:

我是 AngularJS 的新手,正在尝试创建我的第一个自定义指令。

实际上,我创建了两个指令,每个指令都使用它自己的控制器。也许我弄错了,但我希望每个指令控制器都使用它自己的隔离 $scope。但在“指令一”的模板中,我可以从“指令二”调用变量,反之亦然。

如何为每个指令获得一个独立的 $scope,以便每个指令的模板只能使用它自己的变量?

index.html:

<!DOCTYPE html>
<html ng-app="application">

  <head>
    <script src="https://code.angularjs.org/1.2.28/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body>   
    <h1>Testing Custom Directives</h1>
    <hr />
    <directive-one></directive-one>
    <directive-two></directive-two>
  </body>

</html>

script.js:

var app = angular.module('application', [ ]);

app.directive('directiveOne', function(){
  return {
    restrict: 'E',
    template: '<h3>Directive 1</h3> {{dirCtrlOne.name}} {{dirCtrlTwo.year}}',
    controller:function(){
        this.name = 'John';
    },
    controllerAs: 'dirCtrlOne'
  }
});

app.directive('directiveTwo', function(){
  return {
    restrict: 'E',
    template: '<h3>Directive 2</h3> {{dirCtrlTwo.year}} {{dirCtrlOne.name}}',
    controller:function(){
        this.year = 1990;
    },
    controllerAs: 'dirCtrlTwo'
  }
});

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    默认情况下,指令继承其父级的范围,并且通过将变量添加到指令的范围内,也会将其添加到父级。这就是为什么您的两个指令都可以访问其他变量的原因。为了使范围隔离,请尝试以下代码:

    var app = angular.module('application', [ ]);
    
    app.directive('directiveOne', function(){
      return {
       restrict: 'E',
       scope: true,
       template: '<h3>Directive 1</h3> {{dirCtrlOne.name}} {{dirCtrlTwo.year}}',
       controller:function(){
         this.name = 'John';
       },
       controllerAs: 'dirCtrlOne'
     }
    });
    
    app.directive('directiveTwo', function(){
       return {
          restrict: 'E',
          scope: true,
          template: '<h3>Directive 2</h3> {{dirCtrlTwo.year}}   {{dirCtrlOne.name}}',
          controller:function(){
           this.year = 1990;
        },
        controllerAs: 'dirCtrlTwo'
     }
    });
    

    【讨论】:

      【解决方案2】:

      在您的指令中写入scope: {},将指令的范围与任何父范围隔离

      来自AngularJS documentation

      顾名思义,指令的isolate作用域就是isolates 除了您明确添加到范围的模型之外的所有内容:{} 哈希对象。这在构建可重用组件时很有帮助,因为 它可以防止组件更改您的模型状态,除了 您明确传入的模型。

      【讨论】:

        猜你喜欢
        • 2015-08-04
        • 1970-01-01
        • 2016-05-25
        • 1970-01-01
        • 2014-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多