当使用replace时,Angular隔离了模板中不可见的作用域值



我正在创建一个小应用程序,我有以下模板指令。

smallgrid.directive.js:

angular.module('myActions')
    .directive('smallgrid', ['$rootScope', function($rootScope) {
        return {
            restrict: "E",
            scope: {
                actionable: "="
            },
            controller: function($scope) {
                $scope.setLocation = function() {
                    console.log("yee");
                };
            }
        };
    }])
    .directive('three', function() {
        return {
            replace: true,
            templateUrl: '/app/my_actions/directives/templates/grid3x3.template.html'
        };
    })
    .directive('four', function() {
        return {
            replace: true,
            templateUrl: '/app/my_actions/directives/templates/grid4x4.template.html'
        };
    })
    .directive('five', function() {
        return {
            replace: true,
            templateUrl: '/app/my_actions/directives/templates/grid5x5.template.html'
        };
    });

grid3x3.template.html

<div class="k-edit-field" id="board">
    <div class="row" ng-click="setLocation()">
        {{actionable.probability}}
    </div>
</div>

我这样使用这个指令:

<smallgrid three actionable="currentAction.actionable" ng-if="somecondition"></smallgrid>

UI正确呈现。然而,它显示{{actionable.probability}}是空的,并且Click事件没有触发。但是,如果我删除隔离的作用域并直接访问变量,则值是可用的。我明白,当我使用隔离作用域时,在three指令中,我无法访问smallgrid的值。是否有一种方法将这些值从smallgrid传递到模板?

把一个指令作为指令的属性传递,你肯定会有作用域问题。

如果使用ng-transclude对嵌套指令使用范围继承,效果会更好。

起始点应该是

<smallgrid actionable="currentAction.actionable" ng-if="somecondition">
  <three></three>
</smallgrid>

这样<three>就可以访问$parent

function smallgrid() {
  return {
    restrict: "E",
    transclude: true,
    scope: {
      actionable: "="
    },
    template: `<div ng-transclude></div>`,
    controller: function($scope) {
      $scope.setLocation = function() {
        console.log("yee");
      };
    }
  };
}
function three() {
  return {
    template: `<div class="k-edit-field" id="board">
                <div class="row" ng-click="$parent.setLocation()">
                  test = {{$parent.actionable.probability}}
                </div>
              </div>`
  };
}
function myController($scope) {
  $scope.currentAction = {actionable: {probability: "test"}};
  $scope.somecondition = true;
}
angular.module('myApp', []);
angular
    .module('myApp')
    .controller('myController', myController)
    .directive('smallgrid', smallgrid)
    .directive('three', three);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <smallgrid actionable="currentAction.actionable" ng-if="somecondition">
      <three></three>
    </smallgrid>
  </div>
</div>

最新更新