2

我正在创建一个小应用程序,并且该模板具有以下指令。使用替换时,模板中不可见的角度隔离范围值

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中的值传递给模板?

回答

1

将一个指令作为指令的一个属性传递,你肯定会遇到范围问题。

如果对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>

+0

真棒。感谢您的描述性答案。 –