Angular Nested指令

时间:2015-05-29 16:18:48

标签: javascript angularjs angularjs-directive

我正在尝试使用具有隔离范围的子指令执行一个函数。我似乎无法使用Isolated Scope执行其父作用域的函数。它只是不起作用。

UsageA:
<div data-outer data-controller="control"><div data-inner></div></div>

Usage B:
<div data-inner data-controller="controlTwo"></div>


app.controller('control', ['$scope', function($scope){
$scope.onOuterChange = function () {
    alert("Outer Change");
}
}]);

app.controller('controlTwo', ['$scope', function($scope){
$scope.onInnerChange = function () {
    alert("Inner Change");
}
}]);

app.directive('outer', function($compile){
// Runs during compile
return {
    scope: {
        "onOuterChange": "&",
    },
    controller: function ($scope, $element) {
    },
    link: function ($scope, iElm, iAttrs, controller) {
        $scope.onInnerChange = function () {
            alert("Inner Changed");
        }
    }
}
});
app.directive('inner', function($compile){
// Runs during compile
return {
    scope: {
        "onInnerChange": "&",
    },
    controller: function ($scope, $element) {
    },
    link: function ($scope, iElm, iAttrs, controller) {
        $scope.onInnerChange();
    }
}
});

2 个答案:

答案 0 :(得分:0)

在隔离范围内,您还必须在html中指定方法。

<div data-outer on-outer-change="onOuterChange()"><div data-inner></div></div>

答案 1 :(得分:0)

您缺少将on-outer-change添加到具有函数名称的外部指令,该函数名称要传递给隔离的范围指令,如on-outer-change="onOuterChange()"。然后,对于内部指令,您应该将该方法传递给onInnerChange指令隔离范围的inner范围变量。

<强>标记

<div data-outer on-outer-change="onOuterChange()">
    <div data-inner on-inner-change="onOuterChange()"></div>
</div>

<强>代码

app.directive('outer', function($compile) {
  // Runs during compile
  return {
    scope: {
      "onOuterChange": "&",
    },
    restrict: 'A',
    controller: function($scope, $element) {},
    link: function($scope, iElm, iAttrs, controller) {
      $scope.onInnerChange = function() {
        scope.onOuterChange();
      }
    }
  }
});
app.directive('inner', function($compile) {
  // Runs during compile
  return {
    scope: {
      "onInnerChange": "&",
    },
    controller: function($scope, $element) {},
    link: function($scope, iElm, iAttrs, controller) {
      $scope.onInnerChange();
    }
  }
});

Demo here