【问题标题】:Angular - understanding directive isolated scope methodAngular - 理解指令隔离范围方法
【发布时间】:2015-05-28 14:20:43
【问题描述】:

看看下面的代码:

html:

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <input type="button" ng-click="talk()" value="outside directive" />
      <div my-element>
        <input type="button" ng-click="talk()" value="inside directive" />
      </div>
    </div>
  </body>

js:

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

app.controller('MainController', function($scope){
  $scope.talk = function() {
    alert('HELLO1');
  }
});

app.directive('myElement', function(){
  return {
    restrict: 'EA',
    scope: {},
    controller: function($scope) {
      $scope.talk = function() {
        alert('HELLO2');
      }
    }
  };
});

如您所见,有一个控制器,它嵌套了一个指令。

有 2 个按钮,一个在控制器级别(指令之外),一个在指令my-element 内。

主控制器定义了一个作用域方法talk,嵌套指令控制器也定义了一个方法-talk-但请记住该指令具有隔离作用域(我希望talk 方法不会继承到指令的范围内)。

两个按钮都会发出“HELLO 1”的警报,而我希望第二个按钮(指令内部)按照指令控制器中的定义发出“HELLO 2”的警报,但它没有 - 为什么?

我在这里错过了什么?当第二个按钮会提示“HELLO 2”但具有相同的方法名称(“talk”)时,我怎么能得到结果?

谢谢大家

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    如果希望内部内容使用指令作用域,则需要使用手动嵌入:

    app.directive('myElement', function(){
      return {
        restrict: 'EA',
        scope: {},
        transclude: true,
        link: function(scope, element, attr, ctrl, transclude) {
             transclude(scope, function(clone, scope) {
                 element.append(clone);
             });
        },
        controller: function($scope) {
          $scope.talk = function() {
            alert('HELLO2');
          }
        }
      };
    });
    

    默认情况下,被嵌入的内容使用指令范围的兄弟。我实际上不知道 angular 如何处理不使用 transclude 的指令的 DOM 内容(这就是使这个问题变得有趣的原因),但我会从您看到的行为中假设这些元素默认使用指令的父范围.

    【讨论】:

      【解决方案2】:

      这对你有用

      <body ng-app="myApp">
          <div ng-controller="MainController">
              <input type="button" ng-click="talk()" value="outside directive" />
              <div my-element></div>
          </div>
      </body>
      
      app.directive('myElement', function(){
          return {
              restrict: 'A',
              template: '<input type="button" ng-click="talk()" value="inside directive">',
              replace: true,
              scope: {},
              controller: function($scope) {
                  $scope.talk = function() {
                      alert('HELLO2');
                  }
              }
          };
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-26
        • 1970-01-01
        相关资源
        最近更新 更多